0% found this document useful (0 votes)
23 views

Length of Smallest Window in String

This C++ code finds the length of the smallest window in a string that contains all characters that occur in the string at least once. It uses two arrays, M1 and M2, to track the frequencies of each character in the current window and full string, and iterates through the string to find the window with the minimum size that satisfies the frequency requirement.

Uploaded by

NEW GEN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Length of Smallest Window in String

This C++ code finds the length of the smallest window in a string that contains all characters that occur in the string at least once. It uses two arrays, M1 and M2, to track the frequencies of each character in the current window and full string, and iterates through the string to find the window with the minimum size that satisfies the frequency requirement.

Uploaded by

NEW GEN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Length of Smallest window in string

#include<bits/stdc++.h>
using namespace std;

int Smallwindow( string str )


{
int small = str.length();
int len = 0;
int count = 0;
int start = 0;

int M2[26] = {0};


int M1[26] = {0};

for( int i=0; i<str.length(); i++ )


{
if( M2[ str[i]-'a' ] == 0 )
len++;
M2[ str[i]-'a' ] = 1;
}

if( len == small )


return len;

for( int i=0; i<str.length(); i++ )


{
M1[ str[i]-'a' ]++;
if( M1[ str[i]-'a' ] <= M2[ str[i]-'a' ] )
count++;

while( count == len )


{
if( small > i-start+1 )
small = i-start+1;

M1[ str[start]-'a' ]--;


if( M1[ str[start]-'a' ] < M2[ str[start]-'a' ] )
count--;
start++;
}
}

return small;
}

int main()
{
int T;
cin>>T;
while( T-- > 0 )
{
string str;
cin>>str;

cout<<Smallwindow( str )<<endl;


}
return 0;
}

You might also like