Problem Overview
Given strings s and t of length m and n respectively, return the minimum length substring of s such that every character in t is present in the substring. The substring can contain duplicate characters.
Example:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"

BANC is the minimum window containing all characters from t.
Brute Force
Intuition
- Store each character’s frequency from
tin a map - Use two nested loops to iterate over all substrings
- Track character frequencies and a
countof matched characters - When
count == t.size(), compare against the current best answer
Code
| |
Complexity
Time - O(m²) Space - O(m + n)
This gives TLE when s and t are large. We need an O(m + n) solution.
Also the subtr take k time.
Optimal Approach — Sliding Window
Intuition
- Expand the right pointer until the window contains all characters of
t - Then shrink from the left while all characters of
tare still present - Track the best valid window using
startandminLeninstead of extracting the substring on every update
Code
| |
Complexity
Time - O(m + n) Space - O(m + n)
What I Got Wrong Earlier
Instead of storing start and minLen, I was computing and storing the substring on every valid window:
| |
s.substr() is O(len) and calling it repeatedly caused TLE.
Instead of this we store the starting index of substring and compute the substring once at the end.
Key Takeaways
- Minimize unnecessary computation inside hot loops — defer
substrextraction to the end - Sliding window problems follow an almost identical pattern: expand right, shrink left, track the best state
