Problem 76

Abstract / Summary

Find the shortest substring in one string that includes all characters from another string.

Note

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

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;
    }
};
45 lines | 1044 bytes | submitted August 9, 2023 | GitHub   9% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (4+ 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 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.35 | σ = 1.49

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 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
54 links | 38 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Minimum Window Substring - Airbnb Interview Question - Leetcode 76'
NeetCode 26 mins
Minimum Window Substring - Airbnb Interview Question - Leetcode 76
YouTube video 'Minimum Window Substring - II using Hashmaps | Hashmaps Interview Questions'
Pepcoding 16 mins
Minimum Window Substring - II using Hashmaps | Hashmaps Interview Questions
YouTube video 'Minimum Window Substring | Leetcode #76'
Techdose 17 mins
Minimum Window Substring | Leetcode #76
YouTube video '[Java] Leetcode 76. Minimum Window Substring [Sliding Window #8]'
Eric Programming 15 mins
[Java] Leetcode 76. Minimum Window Substring [Sliding Window #8]
YouTube video '76. Minimum Window Substring | 5 Improvizations | Sliding Window'
Aryan Mittal 39 mins
76. Minimum Window Substring | 5 Improvizations | Sliding Window
YouTube video 'MINIMUM WINDOW SUBSTRING | LEETCODE # 76 | PYTHON SOLUTION'
Cracking FAANG 29 mins
MINIMUM WINDOW SUBSTRING | LEETCODE # 76 | PYTHON SOLUTION
YouTube video 'Minimum Window Substring (LeetCode 76) | Interview Essential | Sliding Window + Two Pointers'
Nikhil Lohia 22 mins
Minimum Window Substring (LeetCode 76) | Interview Essential | Sliding Window + Two Pointers
YouTube video 'Minimum Window Substring - LeetCode 76 - JavaScript'
AlgoJS 14 mins
Minimum Window Substring - LeetCode 76 - JavaScript
YouTube video 'Minimum Window Substring - Leetcode 76 | Sliding Window | Java & Python'
Code With K5KC 24 mins
Minimum Window Substring - Leetcode 76 | Sliding Window | Java & Python
YouTube video 'Minimum Window Substring - LeetCode 76 - Python  #slidingwindow #leetcode #blind75'
Deepti Talesra 22 mins
Minimum Window Substring - LeetCode 76 - Python #slidingwindow #leetcode #blind75
YouTube video 'Google Interview Coding Question - Leetcode 76: Minimum Window Substring'
Algorithms Casts 27 mins
Google Interview Coding Question - Leetcode 76: Minimum Window Substring
YouTube video '76. Minimum Window Substring || NEETCODE 150'
TechWithSaumya 20 mins
76. Minimum Window Substring || NEETCODE 150
YouTube video 'Leetcode 76: Minimum Window Substring in Telugu | Sliding Window + Hash Maps | Python DSA | srkcodes'
Srk Codes 19 mins
Leetcode 76: Minimum Window Substring in Telugu | Sliding Window + Hash Maps | Python DSA | srkcodes
YouTube video 'Daily Leetcode #935: Oct 22, 2022 - 76. Minimum Window Substring'
Programming Live with Larry 9 mins
Daily Leetcode #935: Oct 22, 2022 - 76. Minimum Window Substring
YouTube video 'FIND Minimum Window Substring - Leetcode 76'
Lit Code 13 mins
FIND Minimum Window Substring - Leetcode 76
YouTube video 'Daily Leetcode #1405: Feb 04, 2024 - 76. Minimum Window Substring'
Programming Live with Larry 14 mins
Daily Leetcode #1405: Feb 04, 2024 - 76. Minimum Window Substring
YouTube video 'Daily Leetcode #502: Aug 15, 2021 - 76. Minimum Window Substring'
Programming Live with Larry 20 mins
Daily Leetcode #502: Aug 15, 2021 - 76. Minimum Window Substring
YouTube video 'Google Coding Interview Question | Leetcode 76 | Minimum Window Substring'
WorkWithGoogler 24 mins
Google Coding Interview Question | Leetcode 76 | Minimum Window Substring
YouTube video 'Leetcode 76 🔥 Minimum Window Substring | NeetCode 150 Sheet | Java Optimal + Handwritten Dry Run'
Study Placement 36 mins
Leetcode 76 🔥 Minimum Window Substring | NeetCode 150 Sheet | Java Optimal + Handwritten Dry Run
YouTube video '18. Leetcode 76. Minimum Window Substring : Javascript'
Web Fusion with Bharadwaj 29 mins
18. Leetcode 76. Minimum Window Substring : Javascript
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 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