Python 0792.py
class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
def match(sub, subPos, full, fullPos):
# subsequence complete
if subPos == len(sub):
return True
# match next letter
next = full.find(sub[subPos], fullPos)
return match(sub, subPos + 1, full, next + 1) if next != -1 else False
result = 0
for w in words:
# Python Regex works but is too slow
#regex = ".*".join([ c for c in w ])
#if re.search(regex, s):
# result += 1
if match(w, 0, s, 0):
result += 1
return result
Difficulty
and has an acceptance rate of about 51% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
- Dynamic Programming
- Hash Table
- Sorting
- String
- Trie
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method numMatchingSubseq that counts how many strings in a list words appear as subsequences of a given string s. A subsequence is a sequence that can be derived from s by deleting zero or more characters without changing the order of the remaining characters. The algorithm relies on a helper function match that recursively checks whether a single word is a subsequence of s. The code deliberately avoids a regular-expression based solution because of its performance cost and instead uses Python’s built-in str.find to locate the next required character efficiently.
Core Logic
Recursive Matching Function
The heart of the solution is the nested function match. It receives four parameters: the candidate subsequence sub, the current index within that subsequence subPos, the full string full, and the current search start position fullPos. The function first checks whether the entire subsequence has been consumed:
if subPos == len(sub):
return True
When this condition is true, the recursion terminates successfully, indicating that every character of sub has been found in order within full.
If the subsequence is not yet complete, the function attempts to locate the next required character (sub[subPos]) in full starting from fullPos:
next = full.find(sub[subPos], fullPos)
The str.find method returns the index of the first occurrence of the character at or after fullPos, or -1 if the character does not appear. The recursion proceeds only when a match is found:
return match(sub, subPos + 1, full, next + 1) if next != -1 else False
If next equals -1, the function returns False immediately, indicating that the subsequence cannot be formed. Otherwise, the recursion advances both the subsequence index and the search position in full, effectively skipping over characters that have already been matched.
Main Loop Over Words
The outer method numMatchingSubseq initializes a counter result to zero and iterates over each word w in the input list words:
result = 0
for w in words:
if match(w, 0, s, 0):
result += 1
return result
For each word, the method invokes match with the starting positions set to zero. If match returns True, the word is counted as a matching subsequence. The final count is returned after all words have been processed.
Edge Cases Handled
The recursive design naturally accommodates several edge conditions. When the candidate subsequence sub is an empty string, the initial check subPos == len(sub) succeeds immediately, causing match to return True. Consequently, an empty word is always counted as a subsequence of any s, including an empty s.
If the full string full is empty while sub is non-empty, the first call to full.find will return -1 because no characters can be found, leading match to return False. This correctly reflects that a non-empty word cannot be a subsequence of an empty string.
When a character required by sub does not appear in the remaining portion of full, full.find yields -1, and the recursion halts with False. This early exit prevents unnecessary deeper recursion once a mismatch is detected.
The implementation also tolerates repeated characters in both sub and full. Because find always starts searching from the current fullPos, it correctly matches each occurrence in order, even when characters repeat consecutively.
Performance Optimizations
The code deliberately replaces a commented-out regular-expression approach with a custom recursive matcher. Regular expressions constructed as ".*".join([c for c in w]) would require the regex engine to backtrack extensively for long strings, leading to poor performance. By using str.find, the algorithm leverages a highly optimized C implementation for substring search, which runs in linear time relative to the length of full for each character lookup.
The recursion is tail-recursive in spirit: each call advances both indices and does not retain additional state beyond the parameters. Although Python does not perform tail-call optimization, the depth of recursion is bounded by the length of the word being checked, which is typically modest compared to the length of s.
The early termination condition if next != -1 else False ensures that the algorithm stops as soon as a required character is missing, avoiding unnecessary work for words that cannot be matched. This short-circuit behavior is especially beneficial when processing a large list of words where many will fail early.
By initializing the search position fullPos to zero for each new word, the algorithm guarantees that each word’s matching process starts from the beginning of s, preserving correctness while still benefiting from the fast find operation.
Overall, the combination of a direct character search, immediate failure on missing characters, and avoidance of heavyweight regex processing yields a solution that scales well for typical input sizes encountered in subsequence counting problems.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful building blocks lined up in a row. You also have a small bag filled with different secret patterns made out of blocks. The goal is to see which of your patterns can be hidden inside the long line.
The code works like a little robot helper. It picks up one pattern from the bag at a time. To check if the pattern fits, the robot looks at the first block in the pattern and searches through the long line to find a matching block. Once it finds one, it marks the spot and moves to the second block in the pattern. It continues to hunt for the next block, but it only looks at the parts of the line that come after the last block it found.
It keeps doing this until every single block in the pattern has been found in the correct order. If the robot manages to find every block in the pattern, it gives a thumbs up and keeps track of that success. If it gets stuck because a block is missing, it skips that pattern and tries the next one from the bag. After looking at all of them, it counts up how many patterns were successful.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fengvyi | C++ | ||||||||
| fpdjsns | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fengvyi | C++ | ||||||||
| fpdjsns | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| ruoru | Rust | ||||||||
| sonugiri1043 | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 392: Is Subsequence
- problem 2062: Count Vowel Substrings of a String
Solved On The Same Day
- problem 2932: Maximum Strong Pair XOR I
- problem 731: My Calendar II
- problem 820: Short Encoding of Words
- problem 911: Online Election
- problem 950: Reveal Cards In Increasing Order
- problem 1023: Camelcase Matching
- problem 1038: Binary Search Tree to Greater Sum Tree
- problem 1170: Compare Strings by Frequency of the Smallest Character
- problem 1171: Remove Zero Sum Consecutive Nodes from Linked List
- problem 1696: Jump Game VI
- problem 2327: Number of People Aware of a Secret
- problem 432: All O`one Data Structure
- problem 732: My Calendar III
- problem 1044: Longest Duplicate Substring
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality