Number of Matching Subsequences (LeetCode 792): Solution and Explanation

Medium
Array
Hash Table
String
Binary Search
Sorting

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

  1. Scan s once and append each index i to pos[s[i]]. Each list is sorted automatically.
  2. For each word, start with cur = -1.
  3. For each letter ch of the word, binary search pos[ch] for the first index greater than cur (bisect_right).
  4. If the search returns the end of the list, no ch remains after cur and the word fails. Otherwise set cur to that index.
  5. If every letter was found, add one to the count. Return the count.

Step-by-step example

s = "abcde", words = ["a","bb","acd","ace"]
  1. Positions: a -> [0], b -> [1], c -> [2], d -> [3], e -> [4].
  2. "a": the first a after -1 is at 0. Matched, count = 1.
  3. "bb": the first b after -1 is at 1. The next b must be after 1, but the list [1] has nothing left. Fails.
  4. "acd": a at 0, c after 0 at 2, d after 2 at 3. Matched, count = 2.
  5. "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 count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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_left with cur instead of bisect_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.