Problem Description
Given a string s and an array of strings words, determine the number of words in words that are subsequences of s. A subsequence is formed by deleting zero or more characters from s without changing the order of the remaining characters.
Key Insights
- Instead of checking each word individually against s, leverage the fact that s is fixed and iterate through it to "advance" pointers for each word.
- Use a mapping (or bucket) from characters to lists of iterators/pointers representing the next character needed by each word.
- As we iterate over s, update the waiting lists and count when a word is fully matched.
- This approach avoids redundant scanning and significantly reduces time complexity.
Space and Time Complexity
Time Complexity: O(n + m) where n is the length of s and m is the total number of characters in all words
Space Complexity: O(m) for storing the waiting pointers for each character in all words
Solution
We initialize a dictionary (hash map) that maps each letter (a-z) to a list of word iterators or pointers. Each word in words is associated with its starting character. Then, iterate through each character in s. For the current character, retrieve and clear its waiting list and advance each word’s pointer. If a word is completely matched (i.e., all its characters have been processed), increment the result counter. Otherwise, push the word pointer into the bucket corresponding to its next required character. This technique efficiently checks for subsequences in a single pass over s with minimal repeated scanning.