|
| 1 | +// TC: O(n) |
| 2 | +// using two pointer lef and right, it visits all elements only once each. |
| 3 | +// SC: O(n + m) |
| 4 | +// 2 hashmap used for checking the given Strings s and t, n is the size of s, m is the size of m |
| 5 | +class Solution { |
| 6 | + public String minWindow(String s, String t) { |
| 7 | + Map<Character, Integer> map = new HashMap<>(); |
| 8 | + |
| 9 | + for (char c : t.toCharArray()) { |
| 10 | + map.put(c, map.getOrDefault(c, 0) + 1); |
| 11 | + } |
| 12 | + |
| 13 | + int required = map.size(); |
| 14 | + int formed = 0; |
| 15 | + |
| 16 | + int left = 0; |
| 17 | + int right = 0; |
| 18 | + int[] ans = {-1, 0, 0}; |
| 19 | + |
| 20 | + Map<Character, Integer> windowCounts = new HashMap<>(); |
| 21 | + |
| 22 | + while (right < s.length()) { |
| 23 | + char c = s.charAt(right); |
| 24 | + windowCounts.put(c, windowCounts.getOrDefault(c, 0) + 1); |
| 25 | + |
| 26 | + if (map.containsKey(c) && |
| 27 | + windowCounts.get(c).intValue() == map.get(c).intValue()) { |
| 28 | + formed += 1; |
| 29 | + } |
| 30 | + |
| 31 | + while (left <= right && formed == required) { |
| 32 | + c = s.charAt(left); |
| 33 | + |
| 34 | + if (ans[0] == -1 || right - left + 1 < ans[0]) { |
| 35 | + ans[0] = right - left + 1; |
| 36 | + ans[1] = left; |
| 37 | + ans[2] = right; |
| 38 | + } |
| 39 | + |
| 40 | + windowCounts.put(c, windowCounts.get(c) - 1); |
| 41 | + if (map.containsKey(c) && |
| 42 | + windowCounts.get(c).intValue() < map.get(c).intValue()) { |
| 43 | + formed -= 1; |
| 44 | + } |
| 45 | + |
| 46 | + left += 1; |
| 47 | + } |
| 48 | + right += 1; |
| 49 | + } |
| 50 | + return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1); |
| 51 | + } |
| 52 | +} |
0 commit comments