Leetcode 792: Number of Matching Subsequences

grid47
grid47
Exploring patterns and algorithms
Aug 19, 2024 7 min read

A sequence where matching subsequences are counted, with each match glowing softly as it is found.
Solution to LeetCode 792: Number of Matching Subsequences Problem

You are given a string s and an array of strings words. Your task is to determine how many words from the array are subsequences of the string s. A subsequence of a string is derived by deleting some or no characters from the original string without altering the order of the remaining characters.
Problem
Approach
Steps
Complexity
Input: The input consists of a string s and an array of strings words.
Example: s = 'abcdefg', words = ['abc', 'abd', 'ac', 'bfg', 'gfg']
Constraints:
• 1 <= s.length <= 5 * 10^4
• 1 <= words.length <= 5000
• 1 <= words[i].length <= 50
• s and words[i] consist of only lowercase English letters.
Output: Return the number of words in words that are subsequences of the string s.
Example: Output: 3
Constraints:
• The result should be an integer.
Goal: The goal is to check whether each word in the words array is a subsequence of the string s.
Steps:
• Create a mapping of each character's position in s for fast look-up.
• For each word in words, try to find the characters in order using the precomputed mapping.
• If all characters of the word are found in order in s, it is considered a subsequence.
Goal: Ensure that the input strings s and words meet the specified constraints.
Steps:
• s and words contain only lowercase letters.
• Each word in words has a length of 50 or less.
Assumptions:
• Both s and words contain only lowercase letters.
• The length of words[i] will not exceed 50 characters.
Input: Input: s = 'abcdefg', words = ['abc', 'abd', 'ac', 'bfg', 'gfg']
Explanation: The words 'abc', 'abd', and 'ac' are subsequences of s, while 'bfg' and 'gfg' are not.

Input: Input: s = 'ahjkslmn', words = ['ahjl', 'ajl', 'hks', 'lsmn']
Explanation: The words 'ahjl', 'ajl', and 'hks' are subsequences of s. 'lsmn' is not.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus