|
| 1 | +package com.thealgorithms.slidingwindow; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | + |
| 5 | +/** |
| 6 | + * Finds the minimum window substring in 's' that contains all characters of 't'. |
| 7 | + * |
| 8 | + * Worst-case performance O(n) |
| 9 | + * Best-case performance O(n) |
| 10 | + * Average performance O(n) |
| 11 | + * Worst-case space complexity O(1) |
| 12 | + * |
| 13 | + * @author https://github.com/Chiefpatwal |
| 14 | + */ |
| 15 | +public final class MinimumWindowSubstring { |
| 16 | + // Prevent instantiation |
| 17 | + private MinimumWindowSubstring() { |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Finds the minimum window substring of 's' containing all characters of 't'. |
| 22 | + * |
| 23 | + * @param s The input string to search within. |
| 24 | + * @param t The string with required characters. |
| 25 | + * @return The minimum window substring, or empty string if not found. |
| 26 | + */ |
| 27 | + public static String minWindow(String s, String t) { |
| 28 | + if (s.length() < t.length()) { |
| 29 | + return ""; |
| 30 | + } |
| 31 | + |
| 32 | + HashMap<Character, Integer> tFreq = new HashMap<>(); |
| 33 | + for (char c : t.toCharArray()) { |
| 34 | + tFreq.put(c, tFreq.getOrDefault(c, 0) + 1); |
| 35 | + } |
| 36 | + |
| 37 | + HashMap<Character, Integer> windowFreq = new HashMap<>(); |
| 38 | + int left = 0; |
| 39 | + int right = 0; |
| 40 | + int minLen = Integer.MAX_VALUE; |
| 41 | + int count = 0; |
| 42 | + String result = ""; |
| 43 | + |
| 44 | + while (right < s.length()) { |
| 45 | + char c = s.charAt(right); |
| 46 | + windowFreq.put(c, windowFreq.getOrDefault(c, 0) + 1); |
| 47 | + |
| 48 | + if (tFreq.containsKey(c) && windowFreq.get(c).intValue() <= tFreq.get(c).intValue()) { |
| 49 | + count++; |
| 50 | + } |
| 51 | + |
| 52 | + while (count == t.length()) { |
| 53 | + if (right - left + 1 < minLen) { |
| 54 | + minLen = right - left + 1; |
| 55 | + result = s.substring(left, right + 1); |
| 56 | + } |
| 57 | + |
| 58 | + char leftChar = s.charAt(left); |
| 59 | + windowFreq.put(leftChar, windowFreq.get(leftChar) - 1); |
| 60 | + if (tFreq.containsKey(leftChar) && windowFreq.get(leftChar) < tFreq.get(leftChar)) { |
| 61 | + count--; |
| 62 | + } |
| 63 | + left++; |
| 64 | + } |
| 65 | + right++; |
| 66 | + } |
| 67 | + return result; |
| 68 | + } |
| 69 | +} |
0 commit comments