Number of Matching Subsequences — LeetCode 792 Python Solution

MediumTrieArrayHash TableStringBinary SearchDynamic ProgrammingSorting
Problem
#792
Pattern
Trie
Reading time
3 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview