Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
Input:
s = "abcde" words = ["a", "bb", "acd", "ace"] Output:
3 ("a", "acd", and "ace" are subsequences of s).
In this solution, we iterate through each word and check if it's a subsequence of the string s using a two-pointer technique.
Time Complexity: O(m * n), where m is the length of s and n is the number of words. This brute force approach checks each word against the entire string s, leading to time limit exceeded (TLE) errors on large inputs.
To optimize the brute force approach, we can precompute the indices of each character in s using a HashMap. Then, for each word, we perform binary search to efficiently find the next character's position in s.
HashMap Preprocessing: We create a HashMap where each character in s maps to a list of its indices. This allows us to quickly locate all occurrences of a character.
Binary Search for Subsequence Check: For each word, we use binary search to find the position of the next character in s after the last found character. This ensures that the characters appear in order while minimizing unnecessary comparisons.
Time Complexity: O(m + n * k * log(l)), where: m is the length of s. n is the number of words. k is the average length of the words. l is the average number of occurrences of a character in s.
This is significantly faster, especially for larger inputs, since we reduce the time spent searching for characters using the precomputed HashMap and binary search.