Minimum Window Substring

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.

Solution

Java
class Solution {
    public String minWindow(String s, String t) {
        if(t.length() > s.length()) return "";
        int minWindowSize = s.length();
        String minWindow = "";
        int l = 0;
        int curr = 0;

        Map<Character,Integer> map = new HashMap<Character,Integer>();
        for(int i = 0; i < t.length(); i++) map.put(t.charAt(i), map.getOrDefault(t.charAt(i), 0) + 1);
        
        while(curr < s.length()) {
            char ch = s.charAt(curr);
            map.put(ch, map.getOrDefault(ch,0) - 1);
            while(isAllChar(map)) {
                if(minWindowSize > (curr - l)) {
                    minWindowSize = curr - l;
                    minWindow = s.substring(l, curr + 1);
                }
                map.put(s.charAt(l), map.getOrDefault(s.charAt(l++),0) + 1);
            }
            curr++;
            if((curr - l) > minWindowSize) map.put(s.charAt(l), map.getOrDefault(s.charAt(l++),0) + 1);
        }

        return minWindow;
        
    }

    private boolean isAllChar(Map<Character, Integer> map) {
        for(Integer val : map.values()) {
            if (val > 0) return false;
        }
        return true;
    }
}
Agnibha Chandra