This "Hard" rated problem asks you to find all starting indices of substrings in s that are a concatenation of every word in a given list words exactly once. All words in the list have the same length. The order of the words in the substring does not matter. For example, if words is ["foo", "bar"], both "foobar" and "barfoo" are valid substrings. This requires finding "permutations" of the word list within a larger string.
This is a classic question at Apple, Microsoft, and Google. It is a complex application of the Sliding Window and Hash Map patterns. It tests your ability to handle multiple constraints: the words have a fixed length, they must all be used, and they must be contiguous. It's a great test of performance optimization, as a naive approach will be too slow. It also assesses your ability to write clean code for a multi-step logic.
The optimal approach uses a Sliding Window with Hash Maps.
words list.L, you can run the sliding window L times, starting at indices 0, 1, ..., L-1.len(words) * L.s = "barfoobazbitfoobaz", words = ["foo", "baz"] Word length L = 3.
A common mistake is not running the sliding window L times. Many candidates only run it once from index 0, missing potential matches that start at indices 1 or 2. Another mistake is recreating the hash map for every single window, which is very inefficient. Instead, you should add and remove words from a single hash map as the window slides. Finally, failing to handle cases where the string s is shorter than the total length of all words is a common edge case error.
To master the Substring with Concatenation of All Words interview pattern, focus on the "Sliding Window with a Step" logic. The fact that all words are the same length is the key piece of information—use it! Explain to your interviewer how you are using the hash map to keep track of the "remaining words" needed for a match.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum Window Substring | Hard | Solve | |
| Count Complete Substrings | Hard | Solve | |
| Number of Substrings Containing All Three Characters | Medium | Solve | |
| Find All Anagrams in a String | Medium | Solve | |
| Longest Substring with At Most K Distinct Characters | Medium | Solve |