Substring with Concatenation of All Words (LeetCode 30): Solution and Explanation
Given a string s and a list of words that all have the same length, find every index in s where some ordering of all the words, joined together, appears. Each word must be used exactly as many times as it occurs in the list.
Intuition
A match has a fixed length, k * w, where k is the number of words and w is the length of one word. The brute force checks every start index, cuts the next k * w letters into k chunks and compares the chunk counts with the word counts. That repeats almost all the work between neighbouring starts.
Notice that a match is always made of whole chunks. If you cut s into w-letter chunks starting at index 0, then every match whose start is a multiple of w is a run of consecutive chunks. The same holds for starts at 1, w + 1, 2w + 1 and so on, if you cut from index 1. So there are only w different ways to cut, called lanes here, and each start index belongs to exactly one lane.
Within a lane the problem becomes a classic sliding window over chunks: grow on the right, shrink on the left when a word shows up too often, clear everything when a chunk is not a word at all, and record the left edge whenever the window holds exactly the k words.
Approach: Sliding window of whole words, one lane per offset
- Count each word in a map
need. Letwbe the word length andkthe number of words. - For each offset
offfrom 0 tow - 1, setleft = off,count = 0and an empty mapseen. - Move
rightoveroff, off + w, off + 2w, ...and read the chunks[right:right + w]. - If the chunk is not in
need, clearseen, setcount = 0and movelefttoright + w. - Otherwise add it to
seenandcount. While its count inseenis aboveneed, remove the chunk atleftand moveleftforward byw. - If
count == k, recordleft, then remove the chunk atleftso the window can keep sliding.
Step-by-step example
s = "barfoothefoobarman", words = ["foo","bar"]
- need = {foo: 1, bar: 1}, w = 3, k = 2.
- Lane 0 chunks: bar(0) foo(3) the(6) foo(9) bar(12) man(15).
- Read bar, then foo: count = 2 = k, so record 0 and drop bar; left = 3.
- Read the: not a word, so clear the window and set left = 9.
- Read foo, then bar: count = 2, record 9 and drop foo. Read man: not a word, clear.
- Lanes 1 and 2 cut s as b|arf|oot|... and ba|rfo|oth|... and never read a single word, so nothing is added. The answer is [0,9].
Code: Python, Java, C++
1class Solution:
2 def findSubstring(self, s: str, words: List[str]) -> List[int]:
3 w, k = len(words[0]), len(words)
4 need = {}
5 for word in words:
6 need[word] = need.get(word, 0) + 1
7 res = []
8 for off in range(w):
9 left, count, seen = off, 0, {}
10 for right in range(off, len(s) - w + 1, w):
11 word = s[right:right + w]
12 if word not in need:
13 seen, count, left = {}, 0, right + w
14 continue
15 seen[word] = seen.get(word, 0) + 1
16 count += 1
17 while seen[word] > need[word]:
18 first = s[left:left + w]
19 seen[first] -= 1
20 count -= 1
21 left += w
22 if count == k:
23 res.append(left)
24 first = s[left:left + w]
25 seen[first] -= 1
26 count -= 1
27 left += w
28 return res1class Solution {
2 public List<Integer> findSubstring(String s, String[] words) {
3 int w = words[0].length(), k = words.length;
4 Map<String, Integer> need = new HashMap<>();
5 for (String word : words) {
6 need.merge(word, 1, Integer::sum);
7 }
8 List<Integer> res = new ArrayList<>();
9 for (int off = 0; off < w; off++) {
10 int left = off, count = 0;
11 Map<String, Integer> seen = new HashMap<>();
12 for (int right = off; right + w <= s.length(); right += w) {
13 String word = s.substring(right, right + w);
14 if (!need.containsKey(word)) {
15 seen.clear();
16 count = 0;
17 left = right + w;
18 continue;
19 }
20 seen.merge(word, 1, Integer::sum);
21 count++;
22 while (seen.get(word) > need.get(word)) {
23 String first = s.substring(left, left + w);
24 seen.merge(first, -1, Integer::sum);
25 count--;
26 left += w;
27 }
28 if (count == k) {
29 res.add(left);
30 String first = s.substring(left, left + w);
31 seen.merge(first, -1, Integer::sum);
32 count--;
33 left += w;
34 }
35 }
36 }
37 return res;
38 }
39}1class Solution {
2public:
3 vector<int> findSubstring(string s, vector<string>& words) {
4 int w = words[0].size(), k = words.size(), n = s.size();
5 unordered_map<string, int> need;
6 for (const string& word : words) {
7 need[word]++;
8 }
9 vector<int> res;
10 for (int off = 0; off < w; off++) {
11 int left = off, count = 0;
12 unordered_map<string, int> seen;
13 for (int right = off; right + w <= n; right += w) {
14 string word = s.substr(right, w);
15 if (!need.count(word)) {
16 seen.clear();
17 count = 0;
18 left = right + w;
19 continue;
20 }
21 seen[word]++;
22 count++;
23 while (seen[word] > need[word]) {
24 seen[s.substr(left, w)]--;
25 count--;
26 left += w;
27 }
28 if (count == k) {
29 res.push_back(left);
30 seen[s.substr(left, w)]--;
31 count--;
32 left += w;
33 }
34 }
35 }
36 return res;
37 }
38};Time and space complexity
O(n * w)
There are w lanes. In each lane every chunk enters the window once and leaves at most once, and each chunk costs O(w) to slice and hash, giving w * (n / w) * w = n * w.
O(k * w)
The two maps hold at most k distinct words of length w.
Other approaches
Check every start index (time O(n * k * w), space O(k * w))
For every i, cut the next k * w letters into k chunks and compare their counts with need, stopping early on a bad chunk. Simple and often accepted, but it repeats the counting for overlapping windows.
Sort the chunks of each window (time O(n * k * w log k), space O(k * w))
Sort the k chunks of each candidate window and compare with the sorted word list. Easy to write, but sorting adds a log factor on top of the brute force.
Common mistakes
- Using a set instead of a count map. Words can repeat, as in Example 2 where "word" is needed twice.
- Only scanning lane 0. A match can start at any index, so you need all w offsets.
- Forgetting to drop the leftmost word after recording a match, which leaves count stuck at k and records wrong indices.
- On a chunk that is not a word, moving left by only one chunk instead of jumping past the bad chunk and clearing the counts.
Frequently asked questions
Why are there exactly w lanes?
Two start indices that differ by a multiple of w cut s into the same chunk grid. So start indices fall into w groups by their remainder mod w, and each group is one lane.
Does the order of the output matter?
No. The problem accepts the indices in any order. This solution produces them lane by lane, so they are not sorted overall.
What if s is shorter than all the words joined?
Then no window can ever reach k words and the answer is an empty list. The loops handle it naturally.
How is this related to Find All Anagrams in a String?
It is the same fixed-content sliding window, except the units are whole words instead of letters, which is why you need the w separate lanes.