Skip to main content

76. Minimum Window Substrings

This page provides solutions for the leetcode problem 76. Minimum Window Substrings.

Problem Explanation

The problem asks us to calculate the smallest window that contains all the elements of the substring t\text{t}.

Solution

This problem can be solved using the Sliding Window technique. More such questions can be found here.

import java.util.HashMap;

public class Solution {

// Finds the minimum window substring in string 's'
// containing all characters from string 't'.
public String minWindow(String s, String t) {
// initialize a HashMap to store character frequencies.
HashMap<Character, Integer> map = new HashMap<>();
int required = 0;

// count the total number of required characters and update the HashMap.
for (int i = 0; i < t.length(); i++) {
char ch = t.charAt(i);
required++;
map.put(ch, map.getOrDefault(ch, 0) + 1);
}

int end = 0, start = 0, min = Integer.MAX_VALUE;
String res = "";

// move the 'end' pointer through string 's'.
while (end < s.length()) {
char ch = s.charAt(end++);

// check if the current character is part of string 't'.
if (map.containsKey(ch)) {
map.put(ch, map.getOrDefault(ch, 0) - 1);
if (map.get(ch) >= 0) required--;

// check if the current window contains all required characters.
while (start < end && required == 0) {
if (min > end - start) {
// Update minimum window and result.
min = end - start;
res = s.substring(start, end);
}

char chs = s.charAt(start++);

// update character frequency in the HashMap.
if (map.containsKey(chs))
map.put(chs, map.getOrDefault(chs, 0) + 1);

if (map.getOrDefault(chs, 0) > 0) required++;
}
}
}

// return the minimum window substring.
return res;
}
}

Complexity

Let's say there are N\text{N} characters in string ss and MM characters in string t\text{t}.

Time complexity

To calculate smallest window that contains all the elements of the substring t\text{t}, solution iterates over all the elements of string s\text{s}, so time complexity will be:

O(N)\text{O(N)}

Space complexity

Solution uses hashmap which has all elements of substring t\text{t}, so space complexity will be:

O(M)\text{O(M)}