Minimum Window Substring – Solution & Complexity
Solution Walkthrough
1. Translate the requirement into counts
- A window is valid only if it contains each character from
tat least as many times astrequires. - That means the problem is not about distinct letters alone; duplicates like the second
aint = "aba"matter too.
2. Brute-force baseline
- Enumerate every substring of
sand count its characters to see whether it coverst. - Even with small optimizations, that approach becomes at least quadratic and is too slow for long strings.
3. Use a variable-size sliding window
- Keep a frequency table for
t, a frequency table for the current window, and a counter tracking how many required character types are currently satisfied. - Expand the right edge until the window becomes valid. Then shrink the left edge while the window stays valid so you can record the shortest valid window ending at this right position.
- Each pointer only moves forward, which keeps the scan linear.
4. Final solution (all languages)
Track the smallest valid window while growing and shrinking the same sliding range exactly once.
5. Common pitfalls
- Forgetting multiplicity:
t = "AABC"needs twoAcharacters, not just presence. - Shrinking the window before recording the current best valid answer.
- Treating character types satisfied as the total number of matched characters; the two counters mean different things.