C++ 0076.cpp
class Solution {
public:
string minWindow(string s, string t) {
int need[256] = { 0 };
for (auto c : t)
need[c]++;
int have[256] = { 0 };
string result;
int left = 0;
for (int right = 0; right < s.size(); right++)
{
// append
auto current = s[right];
have[current]++;
// shrink
while (left < right)
{
auto l = s[left];
if (need[l] >= have[l])
break;
left++;
have[l]--;
}
// match ?
bool ok = true;
for (char c = 'A'; c <= 'z'; c++)
ok &= need[c] <= have[c];
if (!ok)
continue;
auto length = right - left + 1;
if (result.empty() || length < result.size())
result = s.substr(left, length);
}
return result;
}
};
Difficulty
and has an acceptance rate of about 48% (4+ 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 implementation provides a method to locate the smallest contiguous substring of s that contains every character of t at least as many times as it appears in t. It follows the classic sliding-window technique, maintaining two pointers that delimit the current candidate window and adjusting them while tracking character frequencies.
Initialization
Two fixed-size integer arrays of length 256 serve as frequency tables for the ASCII character set. The first array, need, records how many times each character occurs in t. The second array, have, records the counts of characters currently inside the window. An empty string result will hold the best answer found, and left marks the start of the window.
int need[256] = { 0 };
for (auto c : t)
need[c]++;
int have[256] = { 0 };
string result;
int left = 0;
Expanding the Window
A forward loop iterates right over each index of s. For each character encountered, its count in have is incremented, thereby expanding the window to include the new character.
for (int right = 0; right < s.size(); right++) {
auto current = s[right];
have[current]++;
// ...
}
Shrinking the Window
After each expansion, a nested while loop attempts to move left forward as far as possible without discarding a required character. The condition need[l] >= have[l] stops the shrink when removing s[left] would cause the window to lack enough of that character.
while (left < right) {
auto l = s[left];
if (need[l] >= have[l])
break;
left++;
have[l]--;
}
Checking for a Valid Window
A boolean flag ok is computed by iterating over the ASCII range from 'A' to 'z'. For each character, the expression need[c] <= have[c] is combined with logical AND, resulting in true only when every required character meets its quota inside the current window.
bool ok = true;
for (char c = 'A'; c <= 'z'; c++)
ok &= need[c] <= have[c];
If ok is false, the algorithm proceeds to the next right position without further processing.
Updating the Result
When a valid window is identified, its length is calculated as right - left + 1. The algorithm updates result if it is currently empty or if the new window is shorter than the previously stored one. The substring extraction uses s.substr(left, length).
auto length = right - left + 1;
if (result.empty() || length < result.size())
result = s.substr(left, length);
Edge Cases Handled
The code gracefully deals with an empty target string t; the need table remains all zeros, causing the validation loop to succeed immediately, and the first character of s becomes the minimal window. When t contains characters that never appear in s, the validation never succeeds, leaving result empty, which the method returns. Repeated characters in t are accounted for by the frequency tables, ensuring the window must contain each character the required number of times. The shrink loop respects the left boundary, preventing it from overtaking right and guaranteeing that the window never becomes invalid during contraction.
Performance Optimizations
The use of static arrays sized for the full ASCII range provides constant-time access for both incrementing and checking character counts, avoiding the overhead of hash maps. The shrink loop includes an early break condition that stops as soon as a required character would be lost, minimizing unnecessary pointer movement. The validation step iterates over a bounded character range rather than the entire 256-element array, reducing the number of checks per iteration. Additionally, the algorithm skips the result-update logic entirely when the current window fails the ok test, preventing needless substring creation. These choices collectively keep the inner work per iteration lightweight, allowing the method to process the input strings efficiently.
ELI5 - Simplified Explanation
Imagine having a big collection of colorful building blocks and needing to find the smallest box that contains a specific set of toys. This code works like a helper searching through a long line of blocks to find that special group.
First, the code makes a shopping list called need to keep track of exactly which blocks are required and how many of each are needed. Another list called have is created to keep track of the blocks currently inside the section being checked.
The search starts by picking up blocks one by one from the left to the right side of the collection. As each block is picked up, it is added to the have list. When the current section has too many extra blocks that aren't on the list, the helper moves the left side over to make the section smaller. This helps keep the search tight.
After adjusting the size, the code checks if all the required blocks are inside the current section. If everything on the shopping list is accounted for, it looks at how long this group is. If this group is shorter than the best one found so far, it saves this group as the new winner. The search continues until the end of the line, always looking for the tiniest piece that holds everything needed.
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 | Rust | C# | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Rust | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Rust | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| gouthampradhan | Java | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| luangong | C++ | |||||||||||
| MacJim | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| qiyuangong | Python | |||||||||||
| ruoru | Rust | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| wisdompeak | C++ | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin |
Videos
Similar Problems
- problem 30: Substring with Concatenation of All Words
- problem 209: Minimum Size Subarray Sum
- problem 632: Smallest Range Covering Elements from K Lists
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 995: Minimum Number of K Consecutive Bit Flips
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
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