Substring with Concatenation of All Words
HardTop Interview 150 Sliding WindowSamsungTexas InstrumentsProblem
You get a string s and an array words. Every word in words has the
same length, and words may repeat.
A concatenated substring is a piece of s made of all the words, each used exactly once,
joined in some order with nothing in between. Return every starting index of such a piece. The indices can come in any order.
Constraints
- 1 ≤ s.length ≤ 10⁴
- 1 ≤ words.length ≤ 5000
- 1 ≤ words[i].length ≤ 30, and all words have the same length
- s and words[i] use lowercase English letters
Examples: pick one to animate
Solutions
Time: For each of the w offsets, right visits about n / w words and left only moves forward, so each offset costs O(n / w) map operations on w-letter slices. That is w · (n / w) · w = O(n · w).
Space: The count maps hold at most k distinct words of w letters each.
Because every word has length w, a match can only start at one of w alignments.
For each offset, slide a window one whole word at a time, counting words in a map. If a word is not in the list, reset.
If a word appears too often, drop words from the left. When the window holds k words, record left.