Number of Matching Subsequences (LeetCode 792): Solution and Explanation
Given a string s and a list of words, count how many words can be formed from s by deleting characters without reordering the rest.
Intuition
One word is easy: walk s with a pointer and advance through the word whenever the letters match. Doing that for every word costs O(|s|) each, which is 5000 x 50000 steps in the worst case.
The greedy match only ever asks one question: where is the next occurrence of letter ch after position cur? Taking the earliest such occurrence is always safe, because it leaves the most of s for the remaining letters.
If s is scanned once to store each letter's positions in a sorted list, that question becomes a binary search for the first value greater than cur.
Each word now costs O(word length x log |s|), independent of how long s is.
Approach: Letter positions plus binary search
- Scan s once and append each index
itopos[s[i]]. Each list is sorted automatically. - For each word, start with
cur = -1. - For each letter
chof the word, binary searchpos[ch]for the first index greater thancur(bisect_right). - If the search returns the end of the list, no
chremains aftercurand the word fails. Otherwise setcurto that index. - If every letter was found, add one to the count. Return the count.
Step-by-step example
s = "abcde", words = ["a","bb","acd","ace"]
- Positions: a -> [0], b -> [1], c -> [2], d -> [3], e -> [4].
- "a": the first a after -1 is at 0. Matched, count = 1.
- "bb": the first b after -1 is at 1. The next b must be after 1, but the list [1] has nothing left. Fails.
- "acd": a at 0, c after 0 at 2, d after 2 at 3. Matched, count = 2.
- "ace": a at 0, c at 2, e after 2 at 4. Matched, count = 3. Return 3.
Code: Python, Java, C++
1import bisect
2
3
4class Solution:
5 def numMatchingSubseq(self, s: str, words: List[str]) -> int:
6 pos = {}
7 for i, ch in enumerate(s):
8 pos.setdefault(ch, []).append(i)
9 count = 0
10 for word in words:
11 cur = -1
12 ok = True
13 for ch in word:
14 lst = pos.get(ch, [])
15 j = bisect.bisect_right(lst, cur)
16 if j == len(lst):
17 ok = False
18 break
19 cur = lst[j]
20 if ok:
21 count += 1
22 return count1class Solution {
2 public int numMatchingSubseq(String s, String[] words) {
3 List<List<Integer>> pos = new ArrayList<>();
4 for (int c = 0; c < 26; c++) pos.add(new ArrayList<>());
5 for (int i = 0; i < s.length(); i++) {
6 pos.get(s.charAt(i) - 'a').add(i);
7 }
8 int count = 0;
9 for (String word : words) {
10 int cur = -1;
11 boolean ok = true;
12 for (char ch : word.toCharArray()) {
13 List<Integer> lst = pos.get(ch - 'a');
14 int lo = 0, hi = lst.size();
15 while (lo < hi) {
16 int mid = (lo + hi) / 2;
17 if (lst.get(mid) <= cur) lo = mid + 1;
18 else hi = mid;
19 }
20 if (lo == lst.size()) {
21 ok = false;
22 break;
23 }
24 cur = lst.get(lo);
25 }
26 if (ok) count++;
27 }
28 return count;
29 }
30}1class Solution {
2public:
3 int numMatchingSubseq(string s, vector<string>& words) {
4 vector<vector<int>> pos(26);
5 for (int i = 0; i < (int) s.size(); i++) {
6 pos[s[i] - 'a'].push_back(i);
7 }
8 int count = 0;
9 for (const string& word : words) {
10 int cur = -1;
11 bool ok = true;
12 for (char ch : word) {
13 const vector<int>& lst = pos[ch - 'a'];
14 auto it = upper_bound(lst.begin(), lst.end(), cur);
15 if (it == lst.end()) {
16 ok = false;
17 break;
18 }
19 cur = *it;
20 }
21 if (ok) count++;
22 }
23 return count;
24 }
25};Time and space complexity
O(|s| + L log |s|)
Building the position lists is one pass over s. L is the total length of all words, and each letter costs one binary search.
O(|s|)
The position lists together hold every index of s once.
Other approaches
Two pointers per word (time O(|words| * |s|), space O(1))
For each word, scan s from the start and advance through the word on each match. Simple but O(|s|) per word, so it times out when s is long and there are many words.
Bucket words by next needed letter (time O(|s| + L), space O(|words|))
Put every word in a bucket keyed by the letter it is waiting for. Scan s once; for each character, move the words in that bucket on to their next letter's bucket. Words that run out of letters are counted. One pass over s and each word letter is handled once.
Next-occurrence table (time O(26 * |s| + L), space O(26 * |s|))
Precompute next[i][c], the first index at or after i holding letter c. Each word letter is then one table lookup, but the table needs 26 x |s| entries.
Common mistakes
- Using
bisect_leftwithcurinstead ofbisect_right. The next letter must come strictly after the previous match, otherwise a word like "bb" would reuse the same b. - Restarting the scan of s from 0 for every word, which is exactly the slow version this approach avoids.
- Forgetting a letter that never appears in s. Its list is empty, so the search returns 0 == len and the word fails.
- Counting duplicate words only once. Each entry in words counts separately, even when the same string appears twice.
Frequently asked questions
Why is matching each letter as early as possible correct?
Choosing an earlier position for a letter never removes options for the letters after it, since every later position is still available. So if any matching exists, the greedy one finds it.
Why is this problem tagged binary search?
The main speedup is the binary search over each letter's sorted position list, which replaces a linear scan of s.
Should I cache results for repeated words?
It helps when words has many duplicates. A hash map from word to result lets you skip the search for repeats, but the answer still counts every occurrence.