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 Subsequences INPUT String s: a b c d e s = "abcde" Words Array: "a" "bb" "acd" Build Hash Map of s: char --> indices 'a' --> [0] 'b' --> [1] 'c' --> [2] 'd' --> [3] 'e' --> [4] ALGORITHM STEPS 1 Build Index Map Map each char in s to its index positions 2 Check Each Word For each word, verify if it's a subsequence of s 3 Binary Search Find next valid index using binary search 4 Count Matches Increment count for valid subsequences Checking Words: "a" : a in s? --> OK OK "bb" : b,b in s? --> NO NO "acd" : a,c,d in s? --> OK OK (only 1 'b' exists, need 2) FINAL RESULT Matching Subsequences: "a" - MATCH "bb" - NO MATCH "acd" - MATCH Total Count: 2 2 words are subsequences of string "abcde" Key Insight: The Hash Map optimization preprocesses string s to store character positions, enabling O(log n) binary search lookups instead of O(n) linear scans for each character match. Time Complexity: O(|s| + sum(|word|) * log|s|) vs naive O(|s| * number of words) TutorialsPoint - Number of Matching Subsequences | Hash Map Optimization
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