Problem Description
Given a string s and an array of strings words (where all words have the same length), find all starting indices in s of substrings that are a concatenation of each word in words exactly once and without any intervening characters.
Key Insights
- Use the fact that all words are of the same length to slide through s in fixed-size segments.
- Create a frequency map for the words in the array to know the required counts.
- Use a sliding window approach with different starting offsets (0 to wordLength-1) to maintain alignment.
- Expand the window by checking word-sized chunks and adjust (slide) the window when the frequency of a word exceeds its allowed count.
- When the window contains exactly all words, record the starting index.
Space and Time Complexity
Time Complexity: O(n * m) where n is the length of s and m is the number of words (each word check takes constant time due to fixed word length splitting). Space Complexity: O(m) for the frequency map used for the words.
Solution
The solution uses a sliding window exhibiting multiple starting offsets to ensure each word chunk is properly aligned. For each offset, the window slides in increments of wordLength. A hash map tracks the current counts of words found. When a word's count exceeds its allowed frequency (from the input words array), the window is shrunk from the left until the condition is met. If the window size matches total words, the starting index is recorded. This approach efficiently checks each possible concatenation substring.