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 {
public String minWindow(String s, String t) {
HashMap<Character, Integer> map = new HashMap<>();
int required = 0;

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 = "";
while(end < s.length()) {
char ch = s.charAt(end++);

if(map.containsKey(ch)) {
map.put(ch, map.getOrDefault(ch, 0) - 1);
if (map.get(ch) >= 0) required--;

while(start < end && required == 0) {
if(min > end - start) {
min = end - start;
res = s.substring(start, end);
}
char chs = s.charAt(start++);
if(map.containsKey(chs)) map.put(chs, map.getOrDefault(chs, 0) + 1);
if(map.getOrDefault(chs, 0) > 0) required++;
}
}
}
return res;
}
}

Complexity

Let's say there are N\text{N} characters in string s\text{s} and M\text{M} 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)}