Minimum Window Substring LeetCode 76

Given two strings s and t of lengths m and n, find the minimum window substring in s that contains all characters from t, including duplicates. If no such substring exists, return an empty string "". The answer is guaranteed to be unique per test cases.

LeetCode Problem: Minimum Window Substring

Example Cases

  • Input: s = "ADOBECODEBANC", t = "ABC"
    Output: "BANC"
    Explanation: "BANC" is the smallest substring containing 'A', 'B', and 'C' from t.
  • Input: s = "a", t = "a"
    Output: "a"
    Explanation: The single character "a" is the minimum window.
  • Input: s = "a", t = "aa"
    Output: ""
    Explanation: s lacks two 'a's, so no valid window exists.

Constraints

  • m == s.length, n == t.length
  • 1 <= m, n <= 10^5
  • s and t contain uppercase and lowercase English letters.

Solution Code for LeetCode 76

Choose a programming language and solution approach to view the code and implementation notes. Use the Copy button to access raw code.

Code Implementations

Pattern Recognition for Sliding Window

Identifying patterns in the Minimum Window Substring problem is key to solving it efficiently. The table below breaks down the problem's keywords, checks, approaches, and interview strategies.

Keyword Problem Check Solution Approach Interview Thinking
Minimum Window Substring Smallest contiguous substring in s covering all chars in t with frequencies. Variable-size sliding window with two pointers and frequency map. Expand right to include chars, shrink left to minimize. Track smallest valid window.
Contains All Characters Must match exact frequencies of chars in t (duplicates matter). Use frequency maps or arrays for O(1) char counting. Track "required" vs. "formed" chars. Increment formed when a char meets frequency.
Return Empty String Handle cases where s lacks chars from t. Return "" if no valid window found (minLen = ∞). Initialize minLen to infinity; update only on valid windows.
Contiguous Substring Window must be a continuous segment, not a subsequence. Use two pointers (L, R) to maintain contiguity. Rule out sorting or non-contiguous solutions early.
Large Input Size Constraints: m, n <= 10^5, requiring O(n) solution. Sliding window avoids O(n²) substring generation. Recognize O(n³) brute force is impractical; optimize for linear time.
Duplicates in t t="AABB" needs two A’s and two B’s in window. Frequency map tracks exact counts, not just presence. Emphasize frequency matching in explanation to avoid mistakes.
Case Sensitivity Upper/lowercase letters treated as distinct (A ≠ a). Use char-based frequency map respecting case. Clarify case handling with interviewer; assume distinct per constraints.

Related Patterns: Two Pointers, Hash Map, Frequency Counting. Look for problems asking for min/max substring or subarray with inclusion constraints.

FAANG Interview Strategy for LeetCode 76

Approaching LeetCode 76 in a FAANG interview requires a structured explanation that covers the problem, solution progression, and edge cases. Below is a clear strategy to impress interviewers.

5-Step Interview Script

  1. Restate Problem: "We need the smallest contiguous substring of s containing all characters from t, including their frequencies. If none exists, return ''. Example: s='ADOBECODEBANC', t='ABC' → 'BANC'."
  2. Brute Force: "Check all substrings of s (O(n²)) and verify if each contains t’s chars with frequencies (O(n) per check). Total O(n³), too slow for n=10⁵."
  3. Optimized Solution: "Use a sliding window with two pointers. Build a frequency map for t. Expand right pointer, tracking chars. When all chars are found, shrink left pointer to minimize. Track smallest window. Runs in O(m+n)."
  4. Complexity: "Time: O(m+n) as each char is processed twice (L and R pointers). Space: O(k) for frequency maps (k=128 for ASCII)."
  5. Dry Run: "For s='ADOBECODEBANC', t='ABC': Map t={A:1, B:1, C:1}. Expand R to 'ADOBEC' (formed=3), shrink L to minimize, find 'BANC' (length=4) at L=9, R=12."

Common Mistakes to Avoid

  • Ignoring duplicates in t (e.g., t="AABB" needs two A’s, two B’s).
  • Off-by-one errors in substring indices or slicing.
  • Not updating 'formed' count when shrinking window.
  • Missing edge cases like empty t or t longer than s.

Questions to Ask Interviewer

  • Are strings ASCII-only or Unicode? (Affects map size)
  • Is case sensitivity required? (Confirms char comparison)
  • What’s the max length of s and t? (Validates O(n) need)
  • Is the answer guaranteed unique? (Per constraints, yes)

Follow-Up Questions

  • Non-contiguous window? (Use greedy or sorting)
  • Kth smallest window? (Track k windows with a heap)
  • Weighted characters? (Modify frequency map with weights)

Related Problems: LC3, LC438, LC567.

Deep Dive into LeetCode 76

Breaking down the Minimum Window Substring problem helps solidify understanding for coding interviews and practical applications.

Problem Components

  • Inputs: Strings s (length m) and t (length n), both with uppercase/lowercase English letters (m, n ≤ 10⁵).
  • Output: Shortest contiguous substring of s containing all chars from t with correct frequencies, or "" if none exists.
  • Uniqueness: Answer is unique per test cases.

Key Concepts

  • Contiguity: Window must be a continuous substring, not a subsequence.
  • Frequency Matching: Exact counts of chars in t must be met (e.g., t="AABB" needs two A’s, two B’s).
  • Sliding Window: Use variable-size window to find valid substring, then minimize it.

Solution Steps

  1. Build frequency map for t, count unique chars as "required."
  2. Initialize pointers L=0, R=0, window map, and "formed" counter.
  3. Expand R, adding chars to window map. Increment "formed" when a char meets t’s frequency.
  4. When formed equals required, shrink L to minimize window, updating smallest window found.
  5. Track min window indices and length. Return "" if none found.

Dry Run: s="ADOBECODEBANC", t="ABC"

  • Init: t map={A:1, B:1, C:1}, required=3, L=0, R=0, window={}, formed=0, minLen=∞.
  • R=0 ('A'): window={A:1}, formed=1.
  • R=5 ("ADOBEC"): window={A:1, B:1, C:1, D:1, E:1, O:1}, formed=3, length=6.
  • Shrink L: Remove 'A', formed=2, L=1. Continue R.
  • R=12 ("BANC"): window={B:1, A:1, N:1, C:1}, formed=3, length=4, update minLen=4, result="BANC".
  • End: No smaller window. Return "BANC".

Complexity Analysis

  • Time: O(m+n) — O(n) for t map, O(m) for sliding window (each char processed twice).
  • Space: O(k) for frequency maps (k=128 for ASCII, or O(m) for Unicode).

Edge Cases and Applications

Mastering edge cases and real-world use cases strengthens your interview answers and problem understanding.

Edge Cases

  • t.length > s.length: Return "" (impossible).
  • Empty t: Return "" (per clarification).
  • s == t: Return s.
  • No valid window: s="xyz", t="abc" → "".
  • Duplicates: t="AABB", s="ABAB" → "ABAB".
  • Single char: s="a", t="a" → "a".
  • Case sensitivity: A ≠ a (per constraints).

Real-World Applications

  • Text Search: Shortest snippet with all keywords (e.g., search engine previews).
  • Bioinformatics: Smallest DNA sequence with target nucleotides.
  • Log Analysis: Shortest log segment with required events.
  • Data Compression: Minimal substrings for pattern-based compression.

Language-Specific Notes

Implementation details for the sliding window solution vary by programming language. Select a language to view specific optimizations and considerations.

Frequently Asked Questions

LeetCode 76 asks for the smallest contiguous substring of string s that contains all characters from string t, including duplicates. If no such substring exists, return "". For example, s="ADOBECODEBANC", t="ABC" returns "BANC".

Use two pointers (L, R) and a frequency map for t. Expand R to include chars, tracking counts. When all chars are found (formed=required), shrink L to minimize the window. Update the smallest valid window. Time complexity is O(m+n).

Key edge cases include: t longer than s (return ""), empty t (return ""), s == t (return s), no valid window (e.g., s="xyz", t="abc" → ""), duplicates in t (e.g., t="AABB"), and case sensitivity (A ≠ a).

Sliding window is ideal because it handles the "minimum" requirement efficiently. It expands to find a valid substring and contracts to minimize it, achieving O(m+n) time compared to O(n³) for brute force, crucial for large inputs (m, n ≤ 10⁵).

Restate the problem, outline a brute force approach (O(n³)), then propose sliding window (O(m+n)). Walk through a dry run (e.g., s="ADOBECODEBANC", t="ABC"), discuss complexities, and cover edge cases. Ask clarifying questions like ASCII vs. Unicode.

Related problems include LC3 (Longest Substring Without Repeating Characters), LC438 (Find All Anagrams in a String), and LC567 (Permutation in String). These involve sliding window or frequency counting for substring problems.