Skip to content

Commit cc84e12

Browse files
committed
Smallest distinct window problem
1 parent 67e54dc commit cc84e12

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

smallestdistinctwindow.cpp

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
string smallestWindow(string s,string p){
5+
unordered_map<char,int> freqp;
6+
for(char c:p){
7+
freqp[c]++;
8+
}
9+
int distinct=freqp.size();
10+
unordered_map<char,int> freqw;
11+
int count=0;
12+
13+
int l=0,r=0,ans=INT_MAX,ri=-1,li=-1;
14+
bool flag=false;
15+
16+
while(r<s.length()){
17+
while(r<s.length() && count<distinct){
18+
freqw[s[r]]++;
19+
if(freqp.find(s[r])!=freqp.end() && freqw[s[r]]==freqp[s[r]]){
20+
count++;
21+
}
22+
r++;
23+
}
24+
while(l<=r && count==distinct){
25+
if(ans>r-l){
26+
ans=r-l;
27+
li=l;
28+
ri=r;
29+
flag=true;
30+
}
31+
freqw[s[l]]--;
32+
if(freqp.find(s[l])!=freqp.end()&& freqw[s[l]]<freqp[s[l]]){
33+
count--;
34+
}
35+
l++;
36+
}
37+
}
38+
if(!flag){
39+
return "";
40+
}
41+
string res=s.substr(li,ri-li);
42+
return res;
43+
}
44+
45+
int main(){
46+
string s="timetopractice";
47+
string p="toc";
48+
cout<<smallestWindow(s,p);
49+
return 0;
50+
}

0 commit comments

Comments
 (0)