Number of Matching Subsequences - Problem

Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s.

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

For example, "ace" is a subsequence of "abcde".

Input & Output

Example 1 — Basic Case
$ Input: s = "abcde", words = ["a", "bb", "acd"]
Output: 2
💡 Note: "a" is a subsequence of "abcde" (take character at index 0). "bb" is not a subsequence since we only have one 'b'. "acd" is a subsequence (take characters at indices 0, 2, 3).
Example 2 — No Matches
$ Input: s = "dsahjpjauf", words = ["ahjpjau", "ja", "ahbwzgqnuk", "tnmlanowax"]
Output: 2
💡 Note: "ahjpjau" is a subsequence of "dsahjpjauf". "ja" is a subsequence. "ahbwzgqnuk" and "tnmlanowax" are not subsequences.
Example 3 — Single Character
$ Input: s = "wordgoodgoodgoodbestword", words = ["word", "good", "best", "good"]
Output: 4
💡 Note: All words can be found as subsequences in the string s.

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • 1 ≤ words.length ≤ 5000
  • 1 ≤ words[i].length ≤ 50
  • s and words[i] consist of only lowercase English letters

Visualization

Tap to expand
Number of Matching Subsequencess = "abcde""a""bb""acd"words:"a" matches at index 0, "acd" matches at indices 0,2,3Output: 2
Understanding the Visualization
1
Input
String s and array of words to check
2
Process
Check which words can be formed as subsequences
3
Output
Count of valid subsequences
Key Takeaway
🎯 Key Insight: Process multiple words together instead of checking each word individually to minimize redundant scanning of string s.
Asked in
Google 15 Amazon 12 Facebook 8 Microsoft 6
89.4K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen