Problem 30 · LeetCode 30(opens in a new tab)
Substring with Concatenation of All Words
HardHash tables
You are given a string s and a list words in which every word has the same length. A window of s is a match if it is made of all the words in words, each used exactly as many times as it appears in the list, joined together in any order.
Return every index of s where a match begins, in any order.
Example 1
Input: s = "dogcatcatdog", words = ["cat", "dog"] Output: [0, 6] Why: "dogcat" starts at 0 and "catdog" starts at 6
2 more examples and the constraints
Example 2
Input: s = "aaaa", words = ["aa", "aa"] Output: [0] Why: only the whole string holds two copies of "aa"
Example 3
Input: s = "redbluered", words = ["red", "red"] Output: [] Why: "red" never appears twice in a row
Constraints
- 1 ≤ s.length ≤ 10,000
- 1 ≤ words.length ≤ 5,000
- 1 ≤ words[i].length ≤ 30, and all words have the same length
sand the words use only lowercase English letters
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every startO(n · k · L)
- Sliding window per offsetO(n · L)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for s of 10,000 letters and 5,000 one-letter words | Verdict |
|---|---|---|---|
| Check every start | O(n · k · L) | Recounts shared words | |
| Sliding window per offset | O(n · L) | Best; each piece in and out once |
n = length of s, k = number of words, L = length of one word.
Edge cases to test
- Repeated words. In ["aa", "aa"] the window must hold two copies; a set instead of counts would accept one.
- Words longer than s. If k · L is more than the length of s, no window fits: return [].
- Overlapping matches. "foofoofoo" with ["foo", "foo"] matches at 0 and at 3; matches may share letters.
- A stranger in the middle. In "onetwoxonetwo" the x splits the string; the window restarts after it and still finds both sides.
Common mistakes
- Walking only offset 0, which misses matches that start at 1 to L − 1.
- Using a set of words instead of counts, so a duplicated word is only needed once.
- Restarting from scratch at every start, which is Approach 1 again and counts shared words over and over.
How to talk through it
- 1Clarify. Do all words have the same length? Can words repeat, and must each copy be used? Can matches overlap?
- 2Give the brute force. At every start, cut k words and compare counts with
need: O(n · k · L). - 3Find the window. Equal word lengths mean a match lines up on a grid of L letters. Walk each of the L offsets in word-sized steps.
- 4Slide, do not recount. Add a piece on the right, drop from the left when a word has too many copies, and reset at a stranger. O(n · L) time.
- 5Test out loud. Run duplicated words, overlapping matches, and a match that starts at offset 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?