---
# System prepended metadata

title: Untitled

---

#20200123

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

Example:

Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"

Note:
If there is no such window in S that covers all characters in T, return the empty string "".
If there is such window, you are guaranteed that there will always be only one unique minimum window in S.

K : V
A : 1
B : 0
C : 0

count = 2
minLen = 13 -> (5 - 0 + 1 = 6) -> (12 - 9 + 1 = 4)
minLow = 9

l
h
ADOBECODEBANC

```
class Solution {
    public String minWindow(String s, String t) {
        if (s == null || t == null || s.length() == 0 || t.length() == 0 || t.length() > s.length()) {
            return "";
        }
        
        HashMap<Character, Integer> map = new HashMap<>();
        for (char c : t.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
        int low = 0;
        int minLow = 0;
        int count = 0;
        int minLength = s.length() + 1;
        for (int high = 0; high < s.length(); high++) {
            if (map.containsKey(s.charAt(high))) {
                map.put(s.charAt(high), map.get(s.charAt(high)) - 1);
                if (map.get(s.charAt(high)) >= 0) {
                    count++;
                }
                while (count == t.length()) {
                    if (map.containsKey(s.charAt(low))) {
                        map.put(s.charAt(low), map.get(s.charAt(low)) + 1);
                        if (map.get(s.charAt(low)) > 0) {
                            count--;
                        }
                    }
                    if (high - low + 1 < minLength) {
                        minLow = low;
                        minLength = high - low + 1;
                    }
                    low++;
                }
            }
        }
        
        if (minLength > s.length()) {
            return ""; 
        }
        
        return s.substring(minLow, minLow + minLength);
    }
}
```