Check if all substrings are dictionary words
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string-processing skills such as substring enumeration and membership testing against a dictionary, along with algorithmic reasoning about correctness and complexity.
Part 1: Check Whether Every Subsequence of Length >= 3 Is a Dictionary Word
Constraints
- 0 <= len(s) <= 18
- 0 <= len(dictionary) <= 3000
- 1 <= len(word) <= 18 for each word in dictionary
- s and all dictionary words contain only lowercase English letters
Examples
Input: ('cat', ['cat'])
Expected Output: True
Explanation: The only subsequence of length >= 3 is 'cat', which is in the dictionary.
Input: ('cats', ['cat', 'cas', 'cts', 'ats', 'cats'])
Expected Output: True
Explanation: All distinct subsequences of length >= 3 are: 'cat', 'cas', 'cts', 'ats', and 'cats'. All are present.
Input: ('cats', ['cat', 'cts', 'ats', 'cats'])
Expected Output: False
Explanation: The subsequence 'cas' is missing from the dictionary.
Input: ('', [])
Expected Output: True
Explanation: There are no subsequences of length >= 3, so the condition is vacuously true.
Input: ('aaaa', ['aaa', 'aaaa'])
Expected Output: True
Explanation: The distinct subsequences of length >= 3 are 'aaa' and 'aaaa', and both are in the dictionary.
Hints
- Because len(s) is small, a DFS/backtracking solution that generates subsequences is feasible.
- Repeated characters can create duplicate subsequences. A local set at each recursion depth can help avoid exploring duplicate branches.
Part 2: Check Whether Every Subsequence of Length >= 3 Can Be Rearranged Into a Dictionary Word
Constraints
- 0 <= len(s) <= 18
- 0 <= len(dictionary) <= 3000
- 1 <= len(word) <= 18 for each word in dictionary
- s and all dictionary words contain only lowercase English letters
Examples
Input: ('eat', ['tea'])
Expected Output: True
Explanation: The only subsequence of length >= 3 is 'eat', which can be rearranged into 'tea'.
Input: ('abcd', ['cba', 'dba', 'cad', 'dcb', 'dcba'])
Expected Output: True
Explanation: The subsequences 'abc', 'abd', 'acd', 'bcd', and 'abcd' all have matching anagram signatures in the dictionary.
Input: ('abcd', ['cba', 'dba', 'cad', 'dcba'])
Expected Output: False
Explanation: The subsequence 'bcd' has no matching anagram in the dictionary.
Input: ('ab', [])
Expected Output: True
Explanation: There are no subsequences of length >= 3, so the answer is True.
Input: ('aab', ['aba'])
Expected Output: True
Explanation: The only subsequence of length >= 3 is 'aab', and it can be rearranged into 'aba'.
Hints
- Two strings can be rearranged into each other if their character-frequency counts are identical.
- Precompute a signature for each dictionary word, and maintain the current subsequence's frequency counts incrementally during DFS.