Given two strings S and P. Find the smallest window in the string S consisting of all the characters(including duplicates) of the string P. Return “-1” in case there is no such window present. In case there are multiple such windows of same length, return the one with the least starting index.
classSolution { public: //Function to find the smallest window in the string s consisting //of all the characters of string p. string smallestWindow(string s, string p){ unordered_map<char, int> counter; unordered_map<char, int> sCounter; for(auto& ch : p) counter[ch]++; int freq = counter.size(), res = INT_MAX, pos; int l = 0, r = 0, n = s.length(); while(r < n) { while(r < n and freq) { if(counter.count(s[r])) { if(counter[s[r]] == ++sCounter[s[r]]) freq--; } r++; } while(l < r and !freq) { if(res > r - l) { res = r - l; pos = l; } if(counter.count(s[l])) { if(counter[s[l]] == sCounter[s[l]]--) freq++; } l++; } }