Substring with Concatenation of All Words solution explained

Substring with Concatenation of All Words asks for every index where a string contains all the given words, each used exactly once and glued together in any order. Because all words have the same length L, split the scan into L passes, one per starting offset, and slide a window forward one word at a time while counting words against the required multiset; shrink from the left when a word appears too often, and reset when a word is not in the list. The result runs in O(n·L) time, against O(n·m·L) for checking every start.

By Published 7 min read

What is being asked

You have a string s and a list of words that all share one length. A start index is a match if, reading from that index, the next m × L characters can be cut into exactly the listed words, each used as many times as it appears in the list, in any order. Return all matching start indexes; the order of the output usually does not matter. If the list contains the same word twice, the concatenation must contain it twice.

Our own examples
TextWordsStartsWhy
catdogcatbird[cat, dog]0, 3catdog at 0 and dogcat at 3
xxyyxxyy[xx, yy]0, 2, 4Matches overlap; each start is reported
aaaaa[aa, aa]0, 1Starts at offset 0 and offset 1 both work
redbluered[red, red]noneNo stretch has two reds in a row
hi[hello]noneThe text is shorter than one word
Our own examples. Scroll sideways on a small screen.

Why interviewers use it

It is a harder sliding-window problem because the window moves in jumps of L characters, and because the start offset matters: a match at index 1 is invisible to a scan that only looks at indexes 0, L, 2L and so on. Interviewers look for the offset insight, a clean frequency map that handles repeated words, and a careful reset when an unknown word breaks the window.

Brute force: check every start

from collections import Counter

def concat_starts_brute(s, words):
    if not words:
        return []
    size = len(words[0])
    span = size * len(words)
    want = Counter(words)
    hits = []
    for start in range(len(s) - span + 1):
        pieces = [s[start + i * size:start + (i + 1) * size] for i in range(len(words))]
        if Counter(pieces) == want:
            hits.append(start)
    return hits
Reference: at each start, cut m pieces and compare word counts. O(n·m·L).

With n characters, m words and word length L, each start does m slices of length L and a count comparison, so the total is O(n·m·L). An easy improvement is to stop cutting at the first piece that is not in the list or that exceeds its allowed count; it helps on average but not in the worst case.

Faster: one word-step window per offset

  1. Loop over offsetsFor offset from 0 to L - 1, read the text as a sequence of L-length tokens starting at that offset. Every possible match lines up with exactly one offset.
  2. Extend by one wordTake the next token. If it is not a listed word, clear the window and restart just after the token.
  3. Shrink on surplusIf the token now appears more often in the window than in the list, drop tokens from the left until its count is allowed again.
  4. Report full windowsWhen the window holds m tokens, its left edge is a match. Record it, then drop the leftmost token so the window can keep sliding.
from collections import Counter

def concat_starts(s, words):
    if not words or not s:
        return []
    size, total = len(words[0]), len(words)
    want = Counter(words)
    hits = []
    for offset in range(size):
        left = offset
        have = Counter()
        used = 0
        for right in range(offset, len(s) - size + 1, size):
            token = s[right:right + size]
            if token not in want:
                have.clear()
                used = 0
                left = right + size
                continue
            have[token] += 1
            used += 1
            while have[token] > want[token]:
                have[s[left:left + size]] -= 1
                used -= 1
                left += size
            if used == total:
                hits.append(left)
                have[s[left:left + size]] -= 1
                used -= 1
                left += size
    return sorted(hits)
Python: L passes, each a sliding window over word tokens.
function concatStarts(s, words) {
  if (words.length === 0 || s.length === 0) return [];
  const size = words[0].length;
  const total = words.length;
  const want = new Map();
  for (const w of words) want.set(w, (want.get(w) || 0) + 1);
  const hits = [];
  for (let offset = 0; offset < size; offset++) {
    let left = offset;
    let used = 0;
    const have = new Map();
    for (let right = offset; right + size <= s.length; right += size) {
      const token = s.slice(right, right + size);
      if (!want.has(token)) {
        have.clear();
        used = 0;
        left = right + size;
        continue;
      }
      have.set(token, (have.get(token) || 0) + 1);
      used++;
      while (have.get(token) > want.get(token)) {
        const old = s.slice(left, left + size);
        have.set(old, have.get(old) - 1);
        used--;
        left += size;
      }
      if (used === total) {
        hits.push(left);
        const old = s.slice(left, left + size);
        have.set(old, have.get(old) - 1);
        used--;
        left += size;
      }
    }
  }
  return hits.sort((a, b) => a - b);
}
JavaScript: the same passes with Map counts.

Why the window stays correct

Within one offset, a valid match is a run of m consecutive tokens whose counts equal the list's counts. The window keeps the invariant that no token appears more often than allowed. If the window reaches m tokens under that invariant, the counts must match exactly, because m tokens with no surplus over a multiset of size m use every word exactly. Shrinking on surplus only removes starts that cannot work, since any start before the dropped token would still include the surplus copy. An unknown token can never be inside a match, so every start at or before it is dead and the reset is safe.

Running time

n = text length, m = number of words, L = word length
ApproachTimeExtra space
Every start, cut and compareO(n·m·L)O(m·L)
Every start, stop at first bad pieceSame worst case, faster on averageO(m·L)
Word-step window per offsetO(n·L): about n/L tokens per offset, L offsets, each token sliced and hashed in O(L)O(m·L)
n = text length, m = number of words, L = word length. Scroll sideways on a small screen.

Edge cases

  • Text shorter than one word or shorter than the whole concatenation.
  • Repeated words in the list, such as [aa, aa], which must both be found.
  • Words that overlap with each other inside the text, like aaaaa, where several offsets find matches.
  • A word list of one word, where the answer is every occurrence of that word.
  • An unknown token right after a nearly full window, which must clear everything.
  • An empty word list: decide with the interviewer; returning no indexes is a common choice.

Pitfalls

  • Scanning only offset 0 and missing matches that start mid-word.
  • Treating the word list as a set, which breaks on duplicates.
  • Forgetting to drop the leftmost token after recording a match, which stalls the window.
  • Moving the window by one character instead of one word inside a pass.
  • Clearing the counts on an unknown token but not moving the left edge past it.

How to present it

Fictional example

Explaining the offsets before any code
Candidate
Every word has the same length, so from any start the text cuts into words cleanly. The catch is the start can be anywhere, so I'll run one pass per offset from 0 to L minus 1.
Candidate
In each pass I slide a window of whole words with a count map. If a word shows up more than the list allows, I drop words from the left until it doesn't. An unknown word resets the window. When the window holds m words, its left edge is an answer.
Candidate
Each pass reads about n over L words, and slicing a word costs L, so all L passes together are about n times L.

The single-character version of shrink-on-surplus is Longest Substring with At Most K Distinct Characters. Counting windows rather than listing them is the theme of Count Number of Nice Subarrays. For another problem that walks several pointers over a scan, see 3Sum Closest.

Practicing with Natively

Natively, on Mac or Windows, can read a long problem statement like this one from a screenshot in practice and outline the offset-by-offset window with code, which you can run against your own edge cases such as duplicate words. The transcript of your session shows whether you explained the offset insight before diving into code. More on practicing with an AI interview assistant.

Questions people ask

How do you solve Substring with Concatenation of All Words efficiently?

Run one pass per offset from 0 to L - 1. In each pass slide a window of whole words with a count map, shrink on surplus, reset on unknown words, and record the left edge when the window holds all m words.

Why do you need L different starting offsets?

A match can start at any character, but within one pass you step by whole words. Every start lines up with exactly one offset modulo L.

How are duplicate words handled?

Compare counts, not sets. The window may hold each word as many times as it appears in the list, and shrinks when it holds more.

What is the time complexity?

About O(n·L): each offset reads roughly n/L tokens and slicing or hashing a token costs O(L). Checking every start is O(n·m·L).

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP