Are you getting TLE in this problem Smallest window containing 0, 1 and 2?

19 Views Asked by At

enter image description here

Problem link: https://www.geeksforgeeks.org/problems/smallest-window-containing-0-1-and-2--170637/1

Getting TLE after using the sliding window technique that takes O(N) time complexity and space O(1)

The approach I used that gives TLE :

int smallestSubstring(string S) {
        // Code here
        unordered_map<char,int>mp;
        int l=0,r=0;
        int cnt=0;
        int minLen=INT_MAX;
        while(l<=r && r<S.length()){
            char curChar=S[r];
            if(mp[curChar]==0)
            cnt++;
            
            mp[curChar]++;
            
            if(cnt==3){
                
                //contract karde bhai
                while(mp[S[l]]>1){
                    mp[S[l]]--;
                    l++;
                }
                int cur=r-l+1;
                minLen=min(minLen,cur);
                
            }
            r++;
        }
        
        return minLen==INT_MAX?-1:minLen;
    }
1

There are 1 best solutions below

0
Nazim Qureshi On

It seems that in the above problem, you're using a map that takes little time but why give little time if you could do that problem in constant time!. So we will use an array that takes a size of 3 only for containing different char with frequencies.

int smallestSubstring(string S) {
        // Code here
        int mp[3]={0};
        int l=0,r=0;
        int cnt=0;
        int minLen=INT_MAX;
        while(l<=r && r<S.length()){
            char curChar=S[r];
            if(mp[(curChar-'0')%3]==0)
            cnt++;
            
            mp[(curChar-'0')%3]++;
            
            if(cnt==3){
                
                //contract karde bhai
                while(mp[(S[l]-'0')%3]>1){
                    mp[S[l]-'0']--;
                    l++;
                }
                int cur=r-l+1;
                minLen=min(minLen,cur);
                
            }
            r++;
        }
        
        return minLen==INT_MAX?-1:minLen;
    }