KatInterview

76. Minimum Window Substring

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the smallest substring in a given string s that contains all the characters from another string t. The frequency of characters matters, meaning if t has two 'A's, the substring in s must also contain at least two 'A's. If no such substring exists, we should return an empty string.

Solution

Minimum Window Substring in Python

import collections

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        if not t or not s or len(s) < len(t):
            return ""

        # Create a frequency map for characters in t.
        needs = collections.Counter(t)
        
        # 'required' is the total number of characters from t we need to find.
        required = len(t)
        left = 0
        min_len = float('inf')
        min_start = 0

        # Iterate through s with the right pointer.
        for right, char in enumerate(s):
            # If the current character is needed, decrement the required count.
            # needs[char] > 0 implies it's a character from t we haven't found enough of yet.
            if needs[char] > 0:
                required -= 1
            
            # Decrement the count for the current character.
            # If the character is not in t, its count will become negative.
            needs[char] -= 1

            # When required becomes 0, we have a valid window.
            # Now, we try to shrink it from the left.
            while required == 0:
                # Update the minimum window size found so far.
                current_len = right - left + 1
                if current_len < min_len:
                    min_len = current_len
                    min_start = left
                
                # Get the character at the left of the window.
                left_char = s[left]
                
                # We are about to remove left_char from the window, so we "give it back"
                # by incrementing its count in the needs map.
                needs[left_char] += 1
                
                # If the count of left_char becomes positive, it means
                # it was a character we needed, and our window is now missing it.
                # So, we increment the required count.
                if needs[left_char] > 0:
                    required += 1
                
                # Shrink the window by moving the left pointer.
                left += 1

        # If min_len was never updated, it means no valid window was found.
        return "" if min_len == float('inf') else s[min_start : min_start + min_len]

Minimum Window Substring in Java

class Solution {
    public String minWindow(String s, String t) {
        if (t.length() == 0 || s.length() == 0 || s.length() < t.length()) {
            return "";
        }

        // Create a frequency map for characters in t.
        // We use an array of size 128 to cover all ASCII characters.
        int[] needs = new int[128];
        for (char c : t.toCharArray()) {
            needs[c]++;
        }

        int required = t.length(); // Total number of characters we need to find.
        int left = 0;              // Left pointer of the window.
        int minLen = Integer.MAX_VALUE; // Length of the minimum window found so far.
        int minStart = 0;          // Start index of the minimum window.

        // Iterate through s with the right pointer.
        for (int right = 0; right < s.length(); right++) {
            char charRight = s.charAt(right);

            // If the current character is needed, decrement the required count.
            // needs[charRight] > 0 implies it's a character from t we haven't found enough of yet.
            if (needs[charRight] > 0) {
                required--;
            }
            // Decrement the count for the current character.
            // If the character is not in t, its count will become negative.
            needs[charRight]--;

            // When required becomes 0, we have a valid window.
            // Now, we try to shrink it from the left.
            while (required == 0) {
                // Update the minimum window size found so far.
                if (right - left + 1 < minLen) {
                    minLen = right - left + 1;
                    minStart = left;
                }

                // Get the character at the left of the window.
                char charLeft = s.charAt(left);
                // We are about to remove this character from the window,
                // so we "give it back" by incrementing its count in the needs map.
                needs[charLeft]++;

                // If the count of the left character becomes positive, it means
                // it was a character we needed, and our window is now missing it.
                // So, we increment the required count.
                if (needs[charLeft] > 0) {
                    required++;
                }

                // Shrink the window by moving the left pointer.
                left++;
            }
        }

        // If minLen was never updated, it means no valid window was found.
        return minLen == Integer.MAX_VALUE ? "" : s.substring(minStart, minStart + minLen);
    }
}

Minimum Window Substring in C++

class Solution {
public:
    string minWindow(string s, string t) {
        if (t.empty() || s.empty() || s.length() < t.length()) {
            return "";
        }

        // Create a frequency map for characters in t.
        // We use a vector of size 128 to cover all ASCII characters.
        vector<int> needs(128, 0);
        for (char c : t) {
            needs[c]++;
        }

        int required = t.length(); // Total number of characters we need to find.
        int left = 0;              // Left pointer of the window.
        int min_len = INT_MAX;     // Length of the minimum window found so far.
        int min_start = 0;         // Start index of the minimum window.

        // Iterate through s with the right pointer.
        for (int right = 0; right < s.length(); ++right) {
            // If the current character is needed, decrement the required count.
            // needs[s[right]] > 0 implies it's a character from t we haven't found enough of yet.
            if (needs[s[right]] > 0) {
                required--;
            }
            // Decrement the count for the current character.
            // If the character is not in t, its count will become negative.
            needs[s[right]]--;

            // When required becomes 0, we have a valid window.
            // Now, we try to shrink it from the left.
            while (required == 0) {
                // Update the minimum window size found so far.
                if (right - left + 1 < min_len) {
                    min_len = right - left + 1;
                    min_start = left;
                }

                // Get the character at the left of the window.
                // We are about to remove this character from the window,
                // so we "give it back" by incrementing its count in the needs map.
                needs[s[left]]++;

                // If the count of the left character becomes positive, it means
                // it was a character we needed, and our window is now missing it.
                // So, we increment the required count.
                if (needs[s[left]] > 0) {
                    required++;
                }

                // Shrink the window by moving the left pointer.
                left++;
            }
        }

        // If min_len was never updated, it means no valid window was found.
        return min_len == INT_MAX ? "" : s.substr(min_start, min_len);
    }
};

Minimum Window Substring in TypeScript

function minWindow(s: string, t: string): string {
    if (!t || !s || s.length < t.length) {
        return "";
    }

    // Create a frequency map for characters in t.
    const needs: { [key: string]: number } = {};
    for (const char of t) {
        needs[char] = (needs[char] || 0) + 1;
    }

    let required = t.length; // Total number of characters we need to find.
    let left = 0;            // Left pointer of the window.
    let minLen = Infinity;   // Length of the minimum window found so far.
    let minStart = 0;        // Start index of the minimum window.

    // Iterate through s with the right pointer.
    for (let right = 0; right < s.length; right++) {
        const charRight = s[right];

        // If the current character is needed, decrement the required count.
        if (needs[charRight] > 0) {
            required--;
        }
        // Decrement the count for the current character. Initialize if not present.
        needs[charRight] = (needs[charRight] || 0) - 1;

        // When required becomes 0, we have a valid window.
        // Now, we try to shrink it from the left.
        while (required === 0) {
            // Update the minimum window size found so far.
            const currentLen = right - left + 1;
            if (currentLen < minLen) {
                minLen = currentLen;
                minStart = left;
            }

            // Get the character at the left of the window.
            const charLeft = s[left];

            // We are about to remove this character from the window,
            // so we "give it back" by incrementing its count in the needs map.
            needs[charLeft]++;

            // If the count of the left character becomes positive, it means
            // it was a character we needed, and our window is now missing it.
            // So, we increment the required count.
            if (needs[charLeft] > 0) {
                required++;
            }

            // Shrink the window by moving the left pointer.
            left++;
        }
    }

    // If minLen was never updated, it means no valid window was found.
    return minLen === Infinity ? "" : s.substring(minStart, minStart + minLen);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.