Substring with Concatenation of All Words (LeetCode 30): Solution and Explanation

Hard
Hash Table
String
Sliding Window

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

  1. Count each word in a map need. Let w be the word length and k the number of words.
  2. For each offset off from 0 to w - 1, set left = off, count = 0 and an empty map seen.
  3. Move right over off, off + w, off + 2w, ... and read the chunk s[right:right + w].
  4. If the chunk is not in need, clear seen, set count = 0 and move left to right + w.
  5. Otherwise add it to seen and count. While its count in seen is above need, remove the chunk at left and move left forward by w.
  6. If count == k, record left, then remove the chunk at left so the window can keep sliding.

Step-by-step example

s = "barfoothefoobarman", words = ["foo","bar"]
  1. need = {foo: 1, bar: 1}, w = 3, k = 2.
  2. Lane 0 chunks: bar(0) foo(3) the(6) foo(9) bar(12) man(15).
  3. Read bar, then foo: count = 2 = k, so record 0 and drop bar; left = 3.
  4. Read the: not a word, so clear the window and set left = 9.
  5. Read foo, then bar: count = 2, record 9 and drop foo. Read man: not a word, clear.
  6. 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 res
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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.