Skip to content

Commit a00458c

Browse files
committed
Added MinimumWindowSubstring algorithm and test (Sliding Window)
1 parent 4858ec9 commit a00458c

File tree

2 files changed

+91
-0
lines changed

2 files changed

+91
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.thealgorithms.strings;
2+
3+
/**
4+
* Minimum Window Substring
5+
*
6+
* Given two strings s and t, return the minimum window substring of s such that
7+
* every character in t (including duplicates) is included in the window.
8+
*
9+
* If there is no such substring, return an empty string "".
10+
*
11+
* Approach: Sliding Window + Frequency Table.
12+
*
13+
* Time complexity: O(n + m)
14+
* Space complexity: O(1) for ASCII characters.
15+
*
16+
* Reference: https://en.wikipedia.org/wiki/Minimum_window_substring
17+
*/
18+
public final class MinimumWindowSubstring {
19+
20+
private MinimumWindowSubstring() {
21+
throw new UnsupportedOperationException("Utility class");
22+
}
23+
24+
public static String minWindow(String s, String t) {
25+
if (s == null || t == null || s.length() < t.length() || t.isEmpty()) {
26+
return "";
27+
}
28+
29+
int[] need = new int[256];
30+
for (char c : t.toCharArray()) {
31+
need[c]++;
32+
}
33+
34+
int required = 0;
35+
for (int i = 0; i < 256; i++) {
36+
if (need[i] > 0) required++;
37+
}
38+
39+
int l = 0, r = 0, formed = 0;
40+
int[] window = new int[256];
41+
int minLen = Integer.MAX_VALUE, minLeft = 0;
42+
43+
while (r < s.length()) {
44+
char c = s.charAt(r);
45+
window[c]++;
46+
if (need[c] > 0 && window[c] == need[c]) formed++;
47+
48+
while (l <= r && formed == required) {
49+
if (r - l + 1 < minLen) {
50+
minLen = r - l + 1;
51+
minLeft = l;
52+
}
53+
54+
char d = s.charAt(l);
55+
window[d]--;
56+
if (need[d] > 0 && window[d] < need[d]) formed--;
57+
l++;
58+
}
59+
r++;
60+
}
61+
62+
return minLen == Integer.MAX_VALUE ? "" : s.substring(minLeft, minLeft + minLen);
63+
}
64+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.thealgorithms.strings;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class MinimumWindowSubstringTest {
7+
8+
@Test
9+
public void testExample1() {
10+
assertEquals("BANC", MinimumWindowSubstring.minWindow("ADOBECODEBANC", "ABC"));
11+
}
12+
13+
@Test
14+
public void testExample2() {
15+
assertEquals("", MinimumWindowSubstring.minWindow("A", "AA"));
16+
}
17+
18+
@Test
19+
public void testExample3() {
20+
assertEquals("a", MinimumWindowSubstring.minWindow("a", "a"));
21+
}
22+
23+
@Test
24+
public void testExample4() {
25+
assertEquals("t stri", MinimumWindowSubstring.minWindow("test string", "tist"));
26+
}
27+
}

0 commit comments

Comments
 (0)