Skip to content

Commit e736b60

Browse files
Minimum Window Substring: Accepted
1 parent fbfffdf commit e736b60

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -234,3 +234,4 @@ My accepted leetcode solutions to some of the common interview problems.
234234
- [Move Zeroes](problems/src/two_pointers/MoveZeroes.java) (Easy)
235235
- [Remove Duplicates](problems/src/two_pointers/RemoveDuplicates.java) (Easy)
236236
- [Minimum Size Subarray Sum](problems/src/two_pointers/MinimumSizeSubarraySum.java) (Medium)
237+
- [Minimum Window Substring](problems/src/two_pointers/MinimumWindowSubstring.java) (Hard)
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package two_pointers;
2+
3+
/**
4+
* Created by gouthamvidyapradhan on 03/12/2017.
5+
*
6+
* Given a string S and a string T, find the minimum window in S which will contain all the characters in
7+
* T in complexity O(n).
8+
9+
For example,
10+
S = "ADOBECODEBANC"
11+
T = "ABC"
12+
Minimum window is "BANC".
13+
14+
Note:
15+
If there is no such window in S that covers all characters in T, return the empty string "".
16+
17+
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
18+
19+
Solution O(n). Sliding window sub-sting using two pointers.
20+
21+
*/
22+
public class MinimumWindowSubstring {
23+
private int[] hash = new int[256];
24+
private int[] curr = new int[256];
25+
26+
/**
27+
* Main method
28+
* @param args
29+
* @throws Exception
30+
*/
31+
public static void main(String[] args) throws Exception{
32+
System.out.println(new MinimumWindowSubstring().minWindow("ADOBECODEBANC", "ABC"));
33+
}
34+
35+
public String minWindow(String s, String t) {
36+
if(s.isEmpty() && t.isEmpty()) return "";
37+
if(t.length() > s.length()) return "";
38+
int start = -1, end = -1, min = Integer.MAX_VALUE;
39+
for(int i = 0, l = t.length(); i < l; i ++){
40+
hash[t.charAt(i)]++;
41+
}
42+
43+
for(int i = 0, l = t.length() - 1; i < l; i ++){
44+
curr[s.charAt(i)]++;
45+
}
46+
47+
for(int i = 0, j = t.length() - 1, l = s.length(); j < l;){
48+
curr[s.charAt(j)]++;
49+
if(isMatch()){
50+
if(j - i < min){
51+
min = j - i;
52+
start = i;
53+
end = j;
54+
}
55+
while(j > i){
56+
curr[s.charAt(i)]--;
57+
i ++;
58+
if(isMatch()){
59+
if(j - i < min){
60+
min = j - i;
61+
start = i;
62+
end = j;
63+
}
64+
} else break;
65+
}
66+
}
67+
j ++;
68+
}
69+
if(min == Integer.MAX_VALUE){
70+
return "";
71+
}
72+
return s.substring(start, end + 1);
73+
}
74+
75+
76+
private boolean isMatch(){
77+
for(int i = 0; i < 256; i ++){
78+
if(curr[i] < hash[i]){
79+
return false;
80+
}
81+
}
82+
return true;
83+
}
84+
}

0 commit comments

Comments
 (0)