Taro Logo

Minimum Window Substring

Hard
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+27
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.8K views
Topics:
StringsSliding Windows

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.

Example 1:

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.

Example 2:

Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.

Example 3:

Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.

Constraints:

  • m == s.length
  • n == t.length
  • 1 <= m, n <= 105
  • s and t consist of uppercase and lowercase English letters.

Follow up: Could you find an algorithm that runs in O(m + n) time?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What character set should we expect in strings `s` and `t`? Are we dealing strictly with ASCII characters, or could it include Unicode / emoji characters?
  2. How should we handle cases where `t` contains duplicate characters? For example, if `t` has two 'a's, must the window in `s` also contain at least two 'a's?
  3. What should be returned if `t` is longer than `s`, or if `t` is an empty string?
  4. If there are multiple valid minimum-length windows of the exact same size, does the problem guarantee a unique answer, or should I return any one of them?
  5. Can I assume that string `s` is guaranteed to have a valid window, or do I need to explicitly handle and return an empty string when no such window exists?

Brute Force Solution

Approach

Imagine you need to find the shortest piece of a long word that contains a specific set of required letters. The brute force approach works by examining every single possible slice of the long word from start to finish to see if it contains everything you need.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at every possible starting point in the main text.
  2. For each starting point, look at every possible ending point to create every conceivable slice of the text.
  3. For each slice you create, carefully check every required letter to make sure the slice contains all of them in the necessary amounts.
  4. If a slice does not contain all the required letters, ignore it and move on to the next one.
  5. If a slice does contain all the required letters, measure how long it is.
  6. Keep a running note of the shortest valid slice you have seen so far.
  7. Repeat this process for every single combination of starting and ending points until you have checked them all.
  8. Finally, reveal the shortest valid slice you recorded during your search.

Code Implementation

def min_window(source_string, target_string):
    from collections import Counter
    
    shortest_slice = ""
    minimum_length = float('inf')
    target_counts = Counter(target_string)
    string_length = len(source_string)

    # We test every conceivable starting point to evaluate all possible window positions
    for start_index in range(string_length):
        for end_index in range(start_index, string_length):
            current_slice = source_string[start_index:end_index + 1]
            current_counts = Counter(current_slice)
            
            # We must verify if the current slice satisfies all character quantity demands
            is_valid = True
            for character, count in target_counts.items():
                if current_counts[character] < count:
                    is_valid = False
                    break
            
            if is_valid:
                # We track the minimum length to ensure we isolate the absolute shortest valid window
                if len(current_slice) < minimum_length:
                    minimum_length = len(current_slice)
                    shortest_slice = current_slice

    return shortest_slice

Big(O) Analysis

Time Complexity
O(n² * m) – The brute force approach uses nested loops where the outer loop iterates over every possible starting point in the main text of length n, and the inner loop explores every possible ending point to create slices. Inside these loops, checking each slice against the required letters of length m forces us to inspect the characters within that slice. This means we examine approximately n * n/2 starting and ending combinations, each taking up to n steps multiplied by the requirement check factor m. Multiplying these operations together yields a cubic or quadratic time complexity driven by the nested slice generation, which simplifies to O(n² * m) or O(n³) if m is proportional to n.
Space Complexity
O(1) – The brute force approach examines every possible slice of the main text without creating additional data structures that scale with the input size N. The memory usage relies solely on a few scalar tracking variables, such as indices and length counters, to record the shortest valid slice found so far. Consequently, the auxiliary memory remains constant regardless of how large the input text grows. This results in a final space complexity of O(1).

Optimal Solution

Approach

Instead of checking every possible section of text, we use a smart sliding window strategy that expands and shrinks to find the shortest valid segment. We dynamically track the needed items as we sweep through the text, ensuring we find the best answer efficiently.

Here's how the algorithm would work step-by-step:

  1. Make a list of all the special items you need to find and how many of each you require.
  2. Start with a tiny window of text at the very beginning.
  3. Expand the right side of your window by including more text until your window contains all the special items you need.
  4. Once your window has everything you need, measure its size and remember it if it is the smallest one found so far.
  5. Now, shrink the left side of your window by removing text from the beginning as long as you still have all the special items you need.
  6. Keep measuring and shrinking until you are just about to lose one of the special items you need.
  7. Repeat the process of expanding the right side and shrinking the left side until you reach the end of the entire text.
  8. Finally, reveal the smallest valid window you managed to find during the entire journey.

Code Implementation

def min_window(source_string, target_string):
    from collections import Counter

    required_counts = Counter(target_string)
    unique_target_items = len(required_counts)

    window_start_index = 0
    matched_items_count = 0
    current_window_counts = {}

    minimum_length = float('inf')
    substring_start_index = 0

    # Expand the right side of the window to include new characters until all required items are gathered.
    for window_end_index, current_character in enumerate(source_string):
        current_window_counts[current_character] = current_window_counts.get(current_character, 0) + 1

        if current_character in required_counts and current_window_counts[current_character] == required_counts[current_character]:
            matched_items_count += 1

        # Shrink the left side while the window remains valid to find the shortest possible segment.
        while matched_items_count == unique_target_items:
            current_window_size = window_end_index - window_start_index + 1

            if current_window_size < minimum_length:
                minimum_length = current_window_size
                substring_start_index = window_start_index

            left_character = source_string[window_start_index]
            current_window_counts[left_character] -= 1

            if left_character in required_counts and current_window_counts[left_character] < required_counts[left_character]:
                matched_items_count -= 1

            window_start_index += 1

    # Return the smallest valid substring found or an empty string if no valid window existed.
    if minimum_length == float('inf'):
        return ""

    return source_string[substring_start_index:substring_start_index + minimum_length]

Big(O) Analysis

Time Complexity
O(n) – The right boundary of the sliding window sweeps through every character of the string s of length n exactly once as it expands. The left boundary also moves across the string at most once when shrinking the window to find the optimal size. Since both the expansion and contraction pointers traverse the text linearly without nested restarts, the total number of operations is bounded by 2n. This scales proportionally to n operations, which simplifies to the final Big O time complexity of O(n).
Space Complexity
O(1) – The auxiliary space is dominated by hash maps or frequency arrays used to track the required special items and the current window contents. Since the maximum number of unique characters is bounded by a fixed character set size like the 128 ASCII characters or 26 English letters, the extra memory required remains constant regardless of the input string length N.

Edge Cases

String t is longer than string s
How to Handle:
Return an empty string immediately since it is impossible for s to contain all characters of t.
String t is empty
How to Handle:
Return an empty string because an empty requirement has no valid minimum window substring.
String s is empty
How to Handle:
Return an empty string since no characters are available to form a window.
No valid window exists containing all characters of t
How to Handle:
Return an empty string after the sliding pointer traversal finishes without a successful match.
String t contains duplicate characters
How to Handle:
Track character frequencies using a hash map to ensure all duplicate counts are fully satisfied in the window.
Multiple valid minimum windows of the same length exist
How to Handle:
The problem statement guarantees a unique minimum length window so this scenario will not occur.
String s and t consist of single identical characters
How to Handle:
The sliding window correctly captures the single-character match and returns it in constant time.
Extremely large input strings s and t
How to Handle:
The two-pointer sliding window approach scales efficiently with an optimal linear time complexity of O(N + M).
0/75 completed