#792
Number of Matching Subsequences
MediumArrayHash TableStringBinary SearchDynamic ProgrammingTrieSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n + m), where n is the length of s and m is the total length of words. |
| Space | O(1) | O(m) |
💡
Intuition
Time O(n + m), where n is the length of s and m is the total length of words.Space O(m)
The optimal approach uses a hashmap to group words by their first character and a queue to efficiently check subsequences. This reduces the number of checks needed for each character in `s`.
⚙️
Algorithm
3 steps- 1Step 1: Create a hashmap where each key is a character from `s` and the value is a list of words that start with that character.
- 2Step 2: For each character in `s`, process the words that start with that character by checking if they can be formed as subsequences.
- 3Step 3: Use a queue to track the words and their next character index to check against `s`.
solution.py16 lines
1from collections import defaultdict, deque
2
3def numMatchingSubseq(s, words):
4 waiting = defaultdict(deque)
5 for word in words:
6 waiting[word[0]].append(word)
7 count = 0
8 for char in s:
9 if char in waiting:
10 for _ in range(len(waiting[char])):
11 word = waiting[char].popleft()
12 if len(word) == 1:
13 count += 1
14 else:
15 waiting[word[1]].append(word[1:])
16 return countℹ
Complexity note: This complexity arises because we process each character in `s` and each word only once, making it efficient for larger inputs.
- 1Understanding subsequences is crucial; they maintain order but can skip characters.
- 2Using data structures like hashmaps and queues can significantly optimize the search process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.