Message on Whatsapp 8879355057 for DSA(OA + Interview) + Fullstack Dev Training + 1-1 Personalized Mentoring to get 10+LPA Job
0 like 0 dislike
626 views
in Online Assessments by Expert (46,090 points) | 626 views

2 Answers

0 like 0 dislike
Best answer

Images of ques

image
image

 

by Expert (46,090 points)
0 like 0 dislike

Optimal solution in O(n) time using O(1) memory with two pointers, quite straightforward method. Not used that we could have only 'a','b','c' in the string.

 

int minString(string s){
    
    int i=0,j=s.length()-1;
    for(;i<j && s[i]==s[j];){
        char d=s[i];
        while(i<=j && s[i]==d) i++;
        while(i<=j && s[j]==d) j--;
    }
    return j-i+1;
}
    
int main(void){
    
    cout<<minString("aabcccabba")<<endl;
    cout<<minString("aacbcca")<<endl;
    
    return 0;
}
/* output:
4
1
*/
by Expert (46,090 points)