Similar Problems
Similar Problems not available
Count The Hidden Sequences - Leetcode Solution
Companies:
LeetCode: Count The Hidden Sequences Leetcode Solution
Difficulty: Medium
Topics: prefix-sum array
Problem Description:
Given a string s and an array of strings words, count the number of unique sequences that can be formed by choosing a sequence of words from the array and concatenating them, and removing any characters not in the string s.
Example:
Input: s = "abcde", words = ["a", "bb", "acd", "ace"] Output: 3 Explanation: The possible sequences are "a", "acd", "ace". Note that "bb" cannot be used because "b" is not in the string s.
Solution:
The problem can be solved by using a recursive approach. We start by iterating over the array of words and checking if the first character of each word is present in the string s. If it is present, we call a recursive function with the remaining characters of the string and the remaining words in the array.
The recursive function is responsible for generating all possible sequences by concatenating the words that can be formed using the string and the array of words. It does this by iterating over the array of words and checking if any word can be formed using the current string. If a word can be formed, we call the same recursive function with the remaining characters of the string and the remaining words in the array.
The base case for the recursive function is when the string is empty, in which case we return 1 to indicate that a sequence has been formed. If the array of words is also empty and the string is not empty, we return 0 to indicate that a sequence cannot be formed.
We use a hash set to store the unique sequences formed by the recursive function. Finally, we return the size of the hash set to get the total number of unique sequences.
Here is the Python code:
def countSequences(s, words):
def count(s, words, mem):
if not s:
return 1
if not words:
return 0
if (s, tuple(words)) in mem:
return mem[(s, tuple(words))]
res = 0
for i, word in enumerate(words):
if s[0] not in word:
continue
j = 0
while j < len(s) and j < len(word) and s[j] == word[j]:
j += 1
res += count(s[j:], words[i+1:], mem)
mem[(s, tuple(words))] = res
return res
mem = {}
seqSet = set()
for i, word in enumerate(words):
if s[0] not in word:
continue
j = 0
while j < len(s) and j < len(word) and s[j] == word[j]:
j += 1
if j == len(word):
seqSet.add(word)
else:
res = count(s[j:], words[i+1:], mem)
for seq in res:
seqSet.add(word + seq)
return len(seqSet)
Time Complexity: The time complexity of the algorithm is O(N * 2^N), where N is the length of the string s.
Space Complexity: The space complexity of the algorithm is O(N * 2^N), where N is the length of the string s.
Count The Hidden Sequences Solution Code
1