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
Difficulty
and has an acceptance rate of about 35% (2+ million submissions).
Typical patterns to solve this problem:
- Hash Table
- Sliding Window
- String
AI Disclaimer
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.
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
sis shorter than the total concatenated size, the outer sliding loop never executes because the rangelen(s) - sizeyields a negative bound, resulting in an emptyresult. - If the list
wordscontains duplicate entries, the frequency dictionaryneedcorrectly 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
sdoes not exist in the originalwordslist, its count inneedbecomes 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
0toshift-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 index0.
Performance Optimizations
Several design choices contribute to an efficient execution profile:
- The use of a
defaultdict(int)for theneedmap 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) == 0check 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
shifttimes the number of possible windows. - The initial block construction reuses the same
needdictionary for each offset, avoiding the allocation of additional data structures for the sliding phase. - Updating the
needmap 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.
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.
Code Quality
Complexity Analysis
Other Solutions
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++ |
Videos
Similar Problems
- problem 76: Minimum Window Substring
Solved On The Same Day
- problem 110: Balanced Binary Tree
- problem 111: Minimum Depth of Binary Tree
- problem 118: Pascal's Triangle
- problem 119: Pascal's Triangle II
- problem 228: Summary Ranges
- problem 530: Minimum Absolute Difference in BST
- problem 82: Remove Duplicates from Sorted List II
- problem 102: Binary Tree Level Order Traversal
- problem 103: Binary Tree Zigzag Level Order Traversal
- problem 105: Construct Binary Tree from Preorder and Inorder Traversal
- problem 106: Construct Binary Tree from Inorder and Postorder Traversal
- problem 107: Binary Tree Level Order Traversal II
- problem 109: Convert Sorted List to Binary Search Tree
- problem 117: Populating Next Right Pointers in Each Node II
- problem 128: Longest Consecutive Sequence
- problem 138: Copy List with Random Pointer
- problem 150: Evaluate Reverse Polish Notation
- problem 155: Min Stack
- problem 209: Minimum Size Subarray Sum
- problem 274: H-Index
- problem 380: Insert Delete GetRandom O(1)
- problem 427: Construct Quad Tree
- problem 452: Minimum Number of Arrows to Burst Balloons
- problem 37: Sudoku Solver
- problem 44: Wildcard Matching
- problem 1326: Minimum Number of Taps to Open to Water a Garden
Extra
- 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