|
| 1 | +package com.thealgorithms.strings; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Minimum Window Substring |
| 7 | + * |
| 8 | + * Given two strings s and t, return the minimum window substring of s such that |
| 9 | + * every character in t (including duplicates) is included in the window. |
| 10 | + * |
| 11 | + * If there is no such substring, return an empty string "". |
| 12 | + * |
| 13 | + * Approach: sliding window + frequency table. |
| 14 | + * |
| 15 | + * Time complexity: O(n + m) where n = s.length(), m = t.length() |
| 16 | + * Space complexity: O(1) if using fixed-size arrays for ASCII (256). |
| 17 | + */ |
| 18 | +public final class MinimumWindowSubstring { |
| 19 | + |
| 20 | + private MinimumWindowSubstring() { |
| 21 | + throw new UnsupportedOperationException("Utility class"); |
| 22 | + } |
| 23 | + |
| 24 | + /** |
| 25 | + * Returns the minimum window substring of s that contains all chars from t. |
| 26 | + * |
| 27 | + * @param s source string |
| 28 | + * @param t target string |
| 29 | + * @return shortest substring of s containing all chars of t, or "" if none |
| 30 | + */ |
| 31 | + public static String minWindow(String s, String t) { |
| 32 | + if (s == null || t == null || s.length() < t.length() || t.length() == 0) { |
| 33 | + return ""; |
| 34 | + } |
| 35 | + |
| 36 | + int[] need = new int[256]; |
| 37 | + for (char c : t.toCharArray()) { |
| 38 | + need[c]++; |
| 39 | + } |
| 40 | + |
| 41 | + int required = 0; |
| 42 | + for (int i = 0; i < 256; i++) { |
| 43 | + if (need[i] > 0) required++; |
| 44 | + } |
| 45 | + |
| 46 | + int l = 0, r = 0; |
| 47 | + int formed = 0; |
| 48 | + int[] window = new int[256]; |
| 49 | + int minLen = Integer.MAX_VALUE; |
| 50 | + int minLeft = 0; |
| 51 | + |
| 52 | + while (r < s.length()) { |
| 53 | + char c = s.charAt(r); |
| 54 | + window[c]++; |
| 55 | + if (need[c] > 0 && window[c] == need[c]) { |
| 56 | + formed++; |
| 57 | + } |
| 58 | + |
| 59 | + // Try and contract the window till the point it ceases to be 'desirable'. |
| 60 | + while (l <= r && formed == required) { |
| 61 | + // Update result |
| 62 | + if (r - l + 1 < minLen) { |
| 63 | + minLen = r - l + 1; |
| 64 | + minLeft = l; |
| 65 | + } |
| 66 | + |
| 67 | + char d = s.charAt(l); |
| 68 | + window[d]--; |
| 69 | + if (need[d] > 0 && window[d] < need[d]) { |
| 70 | + formed--; |
| 71 | + } |
| 72 | + l++; |
| 73 | + } |
| 74 | + |
| 75 | + r++; |
| 76 | + } |
| 77 | + |
| 78 | + return minLen == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLen); |
| 79 | + } |
| 80 | +} |
0 commit comments