Minimum Window Substring - Problem

Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window.

If there is no such substring, return the empty string "".

The testcases will be generated such that the answer is unique.

Input & Output

Example 1 — Basic Case
$ Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
💡 Note: The minimum window substring "BANC" includes one 'A', one 'B', and one 'C' from t.
Example 2 — No Valid Window
$ Input: s = "a", t = "aa"
Output: ""
💡 Note: String s only has one 'a', but t requires two 'a's. No valid window exists.
Example 3 — Entire String
$ Input: s = "a", t = "a"
Output: "a"
💡 Note: The minimum window is the entire string s, which is "a".

Constraints

  • 1 ≤ s.length, t.length ≤ 105
  • s and t consist of uppercase and lowercase English letters

Visualization

Tap to expand
Minimum Window Substring INPUT String s: A D O B E C O D E B A N C 0 1 2 3 4 5 6 7 8 9 10 11 12 Target t: A B C Target Hash Map: A: 1 B: 1 C: 1 Input Values s = "ADOBECODEBANC" t = "ABC" m = 13, n = 3 ALGORITHM STEPS 1 Build Target Hash Count char frequency in t 2 Sliding Window Expand right, track chars 3 Contract Window Shrink left when valid 4 Update Minimum Track smallest window Window Hash Progress: A D O B E C O D E B A N C Final Window Complexity Time: O(m + n) Space: O(n) for hash map FINAL RESULT Minimum Window Found: A D O B E C O D E B A N C "BANC" Window Position: Index 9 to 12 Length: 4 Verification Contains 'A': OK Contains 'B': OK Contains 'C': OK OK Key Insight: Use two hash maps: one for target character counts, one for current window counts. The sliding window expands right until all characters are found, then contracts left to minimize. Track "formed" count to know when window contains all required characters with correct frequencies. TutorialsPoint - Minimum Window Substring | Hash Map Approach
Asked in
Facebook 85 Amazon 72 Microsoft 68 Google 65 Apple 45
336.8K Views
Very High Frequency
~25 min Avg. Time
8.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen