From 89cce77372d57c69288c9f738c14cf592abe1dd0 Mon Sep 17 00:00:00 2001 From: ktony Date: Thu, 10 Oct 2024 13:10:23 -0400 Subject: [PATCH] Minimum Window Substring --- minimum-window-substring/TonyKim9401.java | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 minimum-window-substring/TonyKim9401.java diff --git a/minimum-window-substring/TonyKim9401.java b/minimum-window-substring/TonyKim9401.java new file mode 100644 index 000000000..0759effbd --- /dev/null +++ b/minimum-window-substring/TonyKim9401.java @@ -0,0 +1,52 @@ +// TC: O(n) +// using two pointer lef and right, it visits all elements only once each. +// SC: O(n + m) +// 2 hashmap used for checking the given Strings s and t, n is the size of s, m is the size of m +class Solution { + public String minWindow(String s, String t) { + Map map = new HashMap<>(); + + for (char c : t.toCharArray()) { + map.put(c, map.getOrDefault(c, 0) + 1); + } + + int required = map.size(); + int formed = 0; + + int left = 0; + int right = 0; + int[] ans = {-1, 0, 0}; + + Map windowCounts = new HashMap<>(); + + while (right < s.length()) { + char c = s.charAt(right); + windowCounts.put(c, windowCounts.getOrDefault(c, 0) + 1); + + if (map.containsKey(c) && + windowCounts.get(c).intValue() == map.get(c).intValue()) { + formed += 1; + } + + while (left <= right && formed == required) { + c = s.charAt(left); + + if (ans[0] == -1 || right - left + 1 < ans[0]) { + ans[0] = right - left + 1; + ans[1] = left; + ans[2] = right; + } + + windowCounts.put(c, windowCounts.get(c) - 1); + if (map.containsKey(c) && + windowCounts.get(c).intValue() < map.get(c).intValue()) { + formed -= 1; + } + + left += 1; + } + right += 1; + } + return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1); + } +}