Number of Matching Subsequences — LeetCode 792 Python Solution
- Problem
- #792
- Pattern
- Trie
- Reading time
- 3 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "abcde", words = ["a","bb","acd","ace"]
- Output
- 3
- Explanation
- There are three strings in words that are a subsequence of s: "a", "acd", "ace".
Python solution
class Solution:
def numMatchingSubseq(self, s: str, words: List[str]) -> int:
d = defaultdict(deque)
for w in words:
d[w[0]].append(w)
ans = 0
for c in s:
for _ in range(len(d[c])):
t = d[c].popleft()
if len(t) == 1:
ans += 1
else:
d[t[1]].append(t[1:])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Trie
Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 792. Number of Matching Subsequences is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.
The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 792. Number of Matching Subsequences?
- LeetCode 792. Number of Matching Subsequences is rated Medium on LeetCode.
- What is the time complexity of LeetCode 792. Number of Matching Subsequences?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 792. Number of Matching Subsequences?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 792. Number of Matching Subsequences cover?
- LeetCode 792. Number of Matching Subsequences is tagged Trie, Array, Hash Table, String, Binary Search, Dynamic Programming and Sorting on LeetCode.