(String s, String t)
| 1 | class Solution { |
| 2 | |
| 3 | public String minWindow(String s, String t) { |
| 4 | |
| 5 | // map for storing the frequency of elements |
| 6 | Map<Character,Integer> map = new HashMap<>(); |
| 7 | |
| 8 | // storing the default values in the map |
| 9 | for(int i=0; i< t.length() ;i++){ |
| 10 | map.put(t.charAt(i),map.getOrDefault(t.charAt(i),0)+1); |
| 11 | } |
| 12 | |
| 13 | // utility variables |
| 14 | int uniqueCount = map.size(); |
| 15 | int start = 0 , end = 0; |
| 16 | int minLen = Integer.MAX_VALUE , startInd = -1 ; |
| 17 | |
| 18 | // traverse the input string |
| 19 | |
| 20 | while(end<s.length()){ |
| 21 | |
| 22 | // if a character of String "s" is present in String "t" (map) |
| 23 | // then decremment its frequency |
| 24 | |
| 25 | if(map.containsKey(s.charAt(end))) |
| 26 | { |
| 27 | map.put(s.charAt(end),map.get(s.charAt(end))-1); |
| 28 | // if frequency becomes 0 then decrease the value of uniqueCount |
| 29 | // as you have exhausted one of the characterss of "t" |
| 30 | if(map.get(s.charAt(end))==0){ |
| 31 | uniqueCount--; |
| 32 | } |
| 33 | } |
| 34 | // if uniqueCount drops to 0 then it means all unique values of consumed |
| 35 | // you got your window |
| 36 | if(uniqueCount==0){ |
| 37 | // now shrinkig the size of the window! |
| 38 | while (uniqueCount == 0 ){ |
| 39 | // calculate the length and save the minimum length as well as new starting index of the window! |
| 40 | if(minLen > end-start+1){ |
| 41 | minLen = end-start+1; |
| 42 | startInd = start; |
| 43 | } |
| 44 | |
| 45 | if(map.containsKey(s.charAt(start))){ |
| 46 | map.put(s.charAt(start),map.get(s.charAt(start))+1); |
| 47 | if(map.get(s.charAt(start))>0){ |
| 48 | uniqueCount++; |
| 49 | } |
| 50 | } |
| 51 | start++; |
| 52 | } |
| 53 | } |
| 54 | end++; |
| 55 | |
| 56 | } |
| 57 | if(startInd==-1 ){ |
| 58 | return ""; |
| 59 | } |
| 60 | return s.substring(startInd,startInd+minLen); |
nothing calls this directly
no outgoing calls
no test coverage detected