|
| 1 | +//Leetcode 76. Minimum Window Substring |
| 2 | +//Question - https://leetcode.com/problems/minimum-window-substring/ |
| 3 | + |
| 4 | + |
| 5 | +class Solution { |
| 6 | + public String minWindow(String s, String t) { |
| 7 | + //creating a storage to check if the threshold frequency of each character in 't' is met. |
| 8 | + HashMap<Character, Integer> freqTable = new HashMap<Character,Integer>(); |
| 9 | + |
| 10 | + //fill the frequency table |
| 11 | + for(int i=0;i<t.length();i++){ |
| 12 | + char curr = t.charAt(i); |
| 13 | + int freq = 1; |
| 14 | + if(freqTable.containsKey(curr)){ |
| 15 | + freq = freqTable.get(curr); |
| 16 | + freq++; |
| 17 | + } |
| 18 | + freqTable.put(curr,freq); |
| 19 | + } |
| 20 | + |
| 21 | + //initialize the window |
| 22 | + int start = 0; |
| 23 | + int end = 0; |
| 24 | + String ans = ""; |
| 25 | + int windowLen = Integer.MAX_VALUE; |
| 26 | + //keeps the count of distinct characters in 't' which are not yet in the window |
| 27 | + int unmatchedChars = freqTable.size(); |
| 28 | + |
| 29 | + |
| 30 | + //start sliding the window |
| 31 | + while(end<s.length()){ |
| 32 | + char endChar = s.charAt(end); |
| 33 | + |
| 34 | + if(freqTable.containsKey(endChar)){ |
| 35 | + int freq = freqTable.get(endChar); |
| 36 | + freq--; |
| 37 | + freqTable.put(endChar, freq); |
| 38 | + |
| 39 | + //minimum threshold reached for 'endChar' |
| 40 | + if(freq==0) unmatchedChars--; |
| 41 | + } |
| 42 | + |
| 43 | + end++; |
| 44 | + //as long as the threshold of all characters in 't' is maintained. Keep sliding the start of the window to the right. Trimming unnecessarcy characters to minimize window size. |
| 45 | + //The sliding of start of the window to the right is triggered only when the threshold of all characters in 't' is met. |
| 46 | + while(start<s.length() && unmatchedChars==0){ |
| 47 | + char startChar = s.charAt(start); |
| 48 | + |
| 49 | + //update window length and answer after each slide. |
| 50 | + if(end-start<windowLen){ |
| 51 | + windowLen = end-start; |
| 52 | + ans = s.substring(start,end); |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + if(freqTable.containsKey(startChar)){ |
| 57 | + int freq = freqTable.get(startChar); |
| 58 | + freq++; |
| 59 | + freqTable.put(startChar,freq); |
| 60 | + |
| 61 | + //threshold for startChar is not met. sliding the start of window has to be stopped. |
| 62 | + if(freq>0) unmatchedChars++; |
| 63 | + } |
| 64 | + start++; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return ans; |
| 69 | + |
| 70 | + } |
| 71 | +} |
0 commit comments