Skip to content
Problem 792 · LeetCode 792(opens in a new tab)

Number of Matching Subsequences

MediumBinary search

You are given a string s and a list of strings words. Count how many of the words are subsequences of s.

A word is a subsequence of s if you can get it by deleting zero or more letters from s and keeping the rest in their original order. So "bd" fits inside "abcd", while "db" does not. Repeated words in the list each count.

Example 1

Input:  s = "dacab", words = ["ab", "dcb", "bd", "aa"]
Output: 3
Why:    every word but "bd" fits; no d comes after the b
1 more example and the constraints

Example 2

Input:  s = "xyz", words = ["zy", "xz", "xz", "w"]
Output: 2
Why:    both copies of "xz" count; "zy" is out of order

Constraints

  • 1 ≤ length of s ≤ 50,000
  • 1 ≤ number of words ≤ 5,000
  • 1 ≤ length of each word ≤ 50
  • All strings hold only lower-case English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan s for every wordO(w·n)
  2. Letter positions + binary searchO(n + L log n)
  3. Buckets of waiting wordsO(n + L)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 50,000 letters and 5,000 wordsVerdict
Scan s for every wordO(w·n)
Too slow when words miss
Letter positions + binary searchO(n + L log n)
Fast; good for words that arrive later
Buckets of waiting wordsO(n + L)
Best; one pass over s

n = length of s, w = number of words, L = total length of all words.

Edge cases to test

  • Repeated words. ["xz", "xz"] counts 2; do not drop duplicates.
  • Repeated letters in a word. "aa" needs two different a's in s, the second after the first.
  • A letter not in s. A word with such a letter never matches.
  • A word longer than s. It can never fit.
  • A word equal to s. s is a subsequence of itself.

Common mistakes

  • Matching the same letter of s twice for a word like "aa".
  • Checking only that the letters exist in s, not that they come in order.
  • Removing duplicate words, which undercounts.

How to talk through it

  1. 1Clarify. Do duplicate words count twice? Can a word be longer than s?
  2. 2Give the brute force. Two pointers per word: O(w·n), slow when words fail late.
  3. 3Skip the useless letters. Positions per letter plus binary search jump straight to the next match.
  4. 4Read s only once. Keep each word in a bucket for the letter it waits on, and advance a whole bucket per letter.
  5. 5Test out loud. Run "aa", a duplicate word and a word with a missing letter.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?