Solve LeetCode 30: Substring with Concatenation of All Words in Python with a word-aligned windows approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.
This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete 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 |
What the problem is testing
Run one sliding window for each offset modulo the word length. Count fixed-size tokens, shrinking whenever a token exceeds its required frequency.
Algorithm
- Run one sliding window for each offset modulo the word length. Count fixed-size tokens, shrinking whenever a token exceeds its required frequency.
- Maintain this invariant: Every active aligned window contains only known words and never exceeds a required frequency.
- Continue until every input item or reachable state has been resolved, then return the accumulated result.
Python solution
from collections import Counter, defaultdict, deque, OrderedDict
import random
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 answerWhy this is correct
The proof follows the maintained state: Every active aligned window contains only known words and never exceeds a required frequency. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.
Complexity
O(n) time and O(number of distinct words) space. The stated auxiliary space excludes the returned output unless the output is the data structure being built.
Edge cases
Duplicate words require frequency counts; invalid tokens reset the window.
Tested reference code
This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 3. Longest Substring Without Repeating Characters · Next: 76. Minimum Window Substring