Skip to content

Commit 6669d2b

Browse files
authored
Merge pull request #651 from vishvarana/main
Smallest distinct window problem using c++
2 parents 14bec12 + 8472392 commit 6669d2b

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

Strings/smallestdistinctwindow.cpp

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
//Two string given S and P, S being the main string and P being the substring or partial string.
2+
//We need to find the window in main string S which has all the characters of P and display it.
3+
//Time complexity - O(n^2)
4+
//Space complexity - O(1)
5+
6+
#include<bits/stdc++.h>
7+
using namespace std;
8+
9+
string smallestWindow(string s,string p){
10+
unordered_map<char,int> freqp;
11+
for(char c:p){
12+
freqp[c]++; //taking in every character of the partial string
13+
}
14+
int distinct=freqp.size();
15+
unordered_map<char,int> freqw;
16+
int count=0;
17+
18+
int l=0,r=0,ans=INT_MAX,ri=-1,li=-1;
19+
bool flag=false;
20+
21+
while(r<s.length()){
22+
while(r<s.length() && count<distinct){
23+
freqw[s[r]]++; //taking in the main string
24+
if(freqp.find(s[r])!=freqp.end() && freqw[s[r]]==freqp[s[r]]){
25+
count++; //if the char matches than count increased
26+
}
27+
r++; //increment uptil the main string length
28+
}
29+
while(l<=r && count==distinct){
30+
if(ans>r-l){
31+
ans=r-l;
32+
li=l;
33+
ri=r;
34+
flag=true; //setting the flag true if window found
35+
}
36+
freqw[s[l]]--;
37+
if(freqp.find(s[l])!=freqp.end()&& freqw[s[l]]<freqp[s[l]]){
38+
count--;
39+
}
40+
l++;
41+
}
42+
}
43+
if(!flag){
44+
return "";
45+
}
46+
string res=s.substr(li,ri-li);
47+
return res;
48+
}
49+
50+
int main(){
51+
string s="timetopractice";
52+
string p="toc";
53+
cout<<smallestWindow(s,p);
54+
return 0;
55+
}

0 commit comments

Comments
 (0)