Smallest window in a string containing all the characters of another string. |
Given a string S and text T. Output the smallest window in the string S having all characters of the text T. Both the string S and text T contains lowercase English alphabets.
Output the smallest window of the string containing all the characters of the text. If such a window doesn`t exist or this task can not be done then print -1.
Example:
Input:
3
timetopractice
toc
zoomlazapzo
oza
mpsbqedzsqyskjqydomdanqfmtqri
rrbqrnbbzyijnwfnimshbjimbfe
Output:
toprac
apzo
-1
#include <bits/stdc++.h> using namespace std; int main() { //code int t; cin >> t; while (t--) { string s, s1; cin >> s >> s1; unordered_map < char, int > mp; for (int i = 0; i < s1.size(); ++i) { mp[s1[i]]++; } int n = s.size(), r = 0, i = 0, j = 0, l = 0; int miss = s1.size(); while (r < n) { if (mp[s[r]] > 0) { miss -= 1; } mp[s[r]] -= 1; ++r; while (miss == 0) { if (j == 0 || r - l < j - i) { i = l, j = r; } mp[s[l]] += 1; if (mp[s[l]] > 0) { ++miss; } ++l; } } if (j - i != 0) cout << s.substr(i, j - i) << endl; else cout << -1 << endl; } return 0; }