Skip to main content

Most frequently asked interview question #3 with solution





We are given that the string "abc" is valid.
From any valid string V, we may split V into two pieces X and Y such that X + Y (X concatenated with Y) is equal to V.  (X or Y may be empty.)  Then, X + "abc" + Y is also valid.
If for example S = "abc", then examples of valid strings are: "abc", "aabcbc", "abcabc", "abcabcababcc".  Examples of invalid strings are: "abccba", "ab", "cababc", "bac".
Return true if and only if the given string S is valid.


Solution in C++:
   
 bool isValid(string S) {
        vector<char> stack;

        //Iterating over the characters of the string
        for(int iter = 0; iter < S.length(); ++iter){
           
            //Case: Checking
            if(S[iter] == 'c'){

                if(stack.size() < 2){
                    return false;
                }

                if(stack.back() == 'b'){

                    stack.pop_back();
                    if(stack.back() == 'a'){

                        stack.pop_back();
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            } else {

                stack.push_back(S[iter]);
            }
        }
        if(stack.size() == 0) {
            return true;
        } else {
            return false;
        }
    }

Comments