LeetCode 30: Substring with Concatenation of All Words is a Hard sliding window problem. This Python walkthrough develops a word-aligned windows solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Hard |
|---|---|
| Topic | Sliding Window |
| Reusable pattern | word-aligned windows |
| Complexity | O(n) time and O(number of distinct words) space |
Recognizing the pattern
A sliding window fits when validity changes incrementally as the right edge expands and the left edge contracts.
For this problem specifically, run one sliding window for each offset modulo the word length. Count fixed-size tokens, shrinking whenever a token exceeds its required frequency. The invariant worth writing beside the code is: Every active aligned window contains only known words and never exceeds a required frequency.
Step-by-step algorithm
- Identify the input state consumed by
findSubstring(s, words)and initialize the data required by the word-aligned windows pattern. - Run one sliding window for each offset modulo the word length. Count fixed-size tokens, shrinking whenever a token exceeds its required frequency.
- After each update, verify the page’s central invariant: Every active aligned window contains only known words and never exceeds a required frequency.
- Finish only after the boundary behavior is covered: Duplicate words require frequency counts; invalid tokens reset the window.
Python solution
from collections import Counter, defaultdict
class Solution:
def findSubstring(self, s, words):
if not s or not words: return []
width, need, answer = len(words[0]), Counter(words), []
for offset in range(width):
left = offset; used = 0; have = defaultdict(int)
for right in range(offset, len(s) - width + 1, width):
word = s[right:right + width]
if word not in need:
have.clear(); used = 0; left = right + width; continue
have[word] += 1; used += 1
while have[word] > need[word]:
old = s[left:left + width]; have[old] -= 1; used -= 1; left += width
if used == len(words):
answer.append(left)
old = s[left:left + width]; have[old] -= 1; used -= 1; left += width
return answerReading the implementation
The main entry point is findSubstring(s, words). The named working state includes width, left, word, old; those variables make the word-aligned windows state visible instead of hiding it in incidental control flow.
The implementation uses 3 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, run one sliding window for each offset modulo the word length. Count fixed-size tokens, shrinking whenever a token exceeds its required frequency.
Correctness argument
Initialization. Before the scan begins, the unresolved range contains every candidate and the processed range is empty, so no answer has been lost.
Preservation. Run one sliding window for each offset modulo the word length. Count fixed-size tokens, shrinking whenever a token exceeds its required frequency. The chosen movement discards only candidates that cannot improve the answer; afterward, every active aligned window contains only known words and never exceeds a required frequency.
Termination. A boundary advances on every iteration. Once the active range is exhausted, every viable candidate was either measured or safely eliminated, so the stored result is optimal.
Complexity and trade-offs
O(n) time and O(number of distinct words) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Enumerating every substring or subarray is conceptually simple but recomputes almost the same state for overlapping ranges. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
assert sorted(Solution().findSubstring("barfoothefoobarman",["foo","bar"])) == [0,9]Common mistakes and edge cases
- Problem-specific boundary: Duplicate words require frequency counts; invalid tokens reset the window.
- Pattern-level pitfall: Update counts in the correct order when an item enters or leaves, especially when duplicate requirements are present.
- Invariant check: after every update, confirm that every active aligned window contains only known words and never exceeds a required frequency.
Interview review checklist
- Explain why word-aligned windows matches the structure of this input.
- State the invariant in one sentence before tracing code: Every active aligned window contains only known words and never exceeds a required frequency.
- Derive O(n) time and O(number of distinct words) space from how many times each element or state is visited.
- Test the boundary explicitly: Duplicate words require frequency counts; invalid tokens reset the window.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 3. Longest Substring Without Repeating Characters · Next: 76. Minimum Window Substring