Check if all substrings are anagrams of words
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates string-processing skills and combinatorial reasoning about character multisets, specifically anagram recognition, substring enumeration, and the use of efficient representations for repeated checks.
Constraints
- 0 <= len(s) <= 300
- 0 <= len(words) <= 5000
- s and every word in words contain only lowercase English letters 'a' to 'z'
- The total number of characters across all dictionary words is at most 200000
Examples
Input: ("act", ["cat", "dog"])
Expected Output: True
Explanation: The only substring of length at least 3 is "act", which is an anagram of "cat".
Input: ("abca", ["cab", "abca", "zzz"])
Expected Output: True
Explanation: Length-3 substrings are "abc" and "bca", both anagrams of "cab". The full substring "abca" is already in the dictionary.
Input: ("abcd", ["abc", "bcd"])
Expected Output: False
Explanation: The length-3 substrings pass, but the length-4 substring "abcd" has no dictionary anagram.
Input: ("abcb", ["abc", "bbca"])
Expected Output: False
Explanation: "abc" passes, and the full string "abcb" is an anagram of "bbca", but the substring "bcb" is not an anagram of any dictionary word.
Input: ("hi", [])
Expected Output: True
Explanation: There are no substrings of length at least 3, so the condition is vacuously true.
Input: ("aaaa", ["aaa", "aaaa", "aaa"])
Expected Output: True
Explanation: Both length-3 substrings are "aaa", and the full substring is "aaaa". Duplicate dictionary words do not change the answer.
Hints
- Two strings are anagrams exactly when their 26-letter frequency counts are the same.
- Group dictionary words by length, then use a sliding window over `s` for each possible substring length to compare frequency signatures efficiently.