Problem 30

Abstract / Summary

Given a list of words and a string, find if the string contains a substring formed by concatenating all the words exactly once in any order.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0030.py

class Solution:
    def findSubstring(self, s: str, words: List[str]) -> List[int]:
        shift = len(words[0])
        size  = len(words) * shift

        result = []

        for offset in range(shift):
            need = defaultdict(int)
            for w in words:
                need[w] += 1

            # initial block
            pos = offset
            for _ in range(len(words)):
                next = s[pos : pos + shift]
                need[next] -= 1
                if need[next] == 0:
                    del need[next]
                pos += shift

            if len(need) == 0:
                result.append(offset)

            # sliding window
            for left in range(offset, len(s) - size, shift):
                right = left + size
                remove = s[left  : left  + shift]
                add    = s[right : right + shift]

                need[remove] += 1
                need[add]    -= 1

                if need[remove] == 0:
                    del need[remove]
                if need[add]    == 0:
                    del need[add]
                if len(need) == 0:
                    result.append(left + shift)

        return result
41 lines | 1231 bytes | submitted August 31, 2023 | GitHub   6% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 35% (2+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • Sliding Window
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “substring with concatenation of all words” problem. It receives a string s and a list words, where each word has the same length. The goal is to locate every starting index in s where a concatenation of all words appears exactly once and without any intervening characters. The algorithm works by examining the string in parallel windows aligned to the word length, building a frequency map of the required words, and then sliding a fixed-size window across the string while maintaining a dynamic “need” map that reflects the difference between required and observed word counts.

Core Logic

The first step determines the length of each word (shift) and the total length of a concatenated block (size). These values are used throughout the routine to step through the string in increments that preserve word boundaries.

shift = len(words[0])
size  = len(words) * shift

A result list is prepared to collect valid starting positions.

result = []

The outer loop iterates over all possible offsets within a word length. This ensures that every alignment of the sliding window with the word boundaries is examined.

for offset in range(shift):

Inside the offset loop a fresh frequency dictionary need is created from the input words. The dictionary maps each word to the number of times it must appear.

need = defaultdict(int)
for w in words:
    need[w] += 1

Initial Block Construction

For each offset the algorithm first builds an “initial block” that spans exactly len(words) words starting at the current offset. It extracts each word-sized slice, decrements its count in need, and removes the entry when the count reaches zero. This step establishes the baseline state of the window before any sliding occurs.

pos = offset
for _ in range(len(words)):
    next = s[pos : pos + shift]
    need[next] -= 1
    if need[next] == 0:
        del need[next]
    pos += shift

If after processing the initial block the need dictionary is empty, the offset itself is a valid starting index and is added to the result list.

if len(need) == 0:
    result.append(offset)

Sliding Window Mechanics

The algorithm then slides the window one word at a time across the string. For each step it identifies the word leaving the window (remove) and the word entering the window (add). It updates the need map by incrementing the count for the removed word and decrementing the count for the added word, again deleting entries that reach zero. When need becomes empty, the left edge of the window (adjusted by one word length) is recorded as a valid start.

for left in range(offset, len(s) - size, shift):
    right = left + size
    remove = s[left  : left  + shift]
    add    = s[right : right + shift]

    need[remove] += 1
    need[add]    -= 1

    if need[remove] == 0:
        del need[remove]
    if need[add]    == 0:
        del need[add]
    if len(need) == 0:
        result.append(left + shift)

Finally, the accumulated list of starting indices is returned.

return result

Edge Cases Handled

The implementation gracefully manages several boundary conditions:

  • When the input string s is shorter than the total concatenated size, the outer sliding loop never executes because the range len(s) - size yields a negative bound, resulting in an empty result.
  • If the list words contains duplicate entries, the frequency dictionary need correctly records the required multiplicity, and the decrement/increment logic respects these counts during both the initial block and sliding phases.
  • When a word slice extracted from s does not exist in the original words list, its count in need becomes positive after the removal step and negative after the addition step, ensuring that the dictionary never mistakenly treats it as satisfied.
  • The algorithm accounts for all possible alignments by iterating over every offset from 0 to shift-1. This guarantees that substrings starting at any character position that aligns with word boundaries are considered, even when the first word of a valid concatenation does not begin at index 0.

Performance Optimizations

Several design choices contribute to an efficient execution profile:

  • The use of a defaultdict(int) for the need map enables constant-time updates without explicit existence checks, reducing overhead in the inner loops.
  • Deleting entries whose count reaches zero keeps the dictionary size minimal, allowing the len(need) == 0 check to be a cheap operation.
  • By processing the string in strides equal to the word length, the algorithm avoids examining overlapping substrings that cannot possibly form a valid concatenation, thereby limiting the number of iterations to shift times the number of possible windows.
  • The initial block construction reuses the same need dictionary for each offset, avoiding the allocation of additional data structures for the sliding phase.
  • Updating the need map incrementally (adding the outgoing word and removing the incoming word) eliminates the need to recompute the entire frequency map for each window position, turning what could be a quadratic operation into a linear pass over the string for each offset.
written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a long train of colorful alphabet blocks and a box filled with special letter tiles. The goal is to find where to start picking a bunch of blocks from the train so that they perfectly match all the tiles in the box.

First, identify how long each tile is and how many tiles there are in total to know the size of the section to look for. Start by looking at the very beginning of the train. Take a handful of blocks that is exactly the right size and check if those blocks can be rearranged to match exactly what is inside the box.

If they match, remember exactly where that section started. Then, slide the entire handful of blocks one tile forward along the train. When sliding, take away the block that was at the very start of the handful and add the new block that is now at the very end. Check again to see if the new handful matches the box. Keep sliding and checking all the way to the end of the train. Repeat this whole process by starting from different positions until every possible spot has been checked. Gathering all those secret starting spots shows exactly where the matches hide.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 28 | median = 7 | μ = 7.07 | σ = 0.92

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Go PHP TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak Python
XiaotaoGuo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, PHP, Python, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
wisdompeak Python
XiaotaoGuo C++
49 links | 33 authors | 11 languages

Videos

14 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

27 solutions   August 31, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality