MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / minWindow

Method minWindow

minimumWindowSubstrin.java:2–53  ·  view source on GitHub ↗
(String s, String t)

Source from the content-addressed store, hash-verified

1class Solution {
2 public String minWindow(String s, String t) {
3 HashMap<Character,Integer> freqMap = new HashMap<>();
4 //populate the map with t string
5 // T-> M
6 // S -> N
7 //TC -> O(M + 2N)~ O(N+M)
8 //SC -> O(M)
9 for(int i=0;i<t.length();i++){
10 char ch = t.charAt(i);
11 freqMap.put(ch,freqMap.getOrDefault(ch,0)+1);
12 }
13 int uniqueCharCount=freqMap.size();
14 int startIndex=-1;
15 int windowStart=0;
16 int windowEnd=0;
17 int minLen = Integer.MAX_VALUE;
18 int N = s.length();
19 // O(2N)
20 while(windowEnd<N){
21 //Expansion Phase
22 char ch = s.charAt(windowEnd);
23 if(freqMap.containsKey(ch)){
24 freqMap.put(ch,freqMap.get(ch)-1);
25 if(freqMap.get(ch)==0){
26 uniqueCharCount--;
27 }
28 }
29 //Shrinking Phase
30 while(uniqueCharCount==0){
31 //find len
32 int len = windowEnd-windowStart+1;
33 if(len<minLen){
34 minLen = len;
35 startIndex = windowStart;
36 }
37 ch = s.charAt(windowStart);
38 if(freqMap.containsKey(ch)){
39 freqMap.put(ch,freqMap.get(ch)+1);
40 if(freqMap.get(ch)>0){
41 uniqueCharCount++;
42 }
43 }
44 windowStart++;
45 }
46 windowEnd++;
47
48 }
49 if(startIndex==-1){
50 return "";
51 }
52 return s.substring(startIndex,startIndex+minLen);
53 }
54}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected