Check if a string consisting only of a, b, c can be made empty by removing substring “abc” recursively
Given a string S size of N consisting of characters ‘a‘, ‘b‘, and ‘c‘ only, the task is to check if the given string can be made empty by removing the string “abc” recursively or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Input: S = abcabc
Below are the operations performed to empty the string:
- Remove the substring S[3, 5] from the string modifies the string S to “abc”.
- Remove the substring S[0, 2] from the string modifies the string S to “”.
After the above operations, the given string S can be made empty by removing substring “abc”. Therefore, print Yes.
Input: S = abcabcababccc
Approach: The given problem can be solved by using a stack. The idea is to minimize the string to an empty string by removing all occurrences of the “abc”. Follow the steps below to solve the given problem:
- Initialize a stack, say Stack to store the characters of the given string S.
- Traverse the given string S and perform the following steps:
- If the current character is ‘a‘ or ‘b‘, then push it to the stack Stack.
- If the current character is ‘c‘ and the last two characters are ‘b‘ and ‘a‘ respectively, then pop twice from the stack.
- If the current character is ‘c‘ and the last two characters are not ‘b‘ and ‘a‘, then the given string S can not be formed.
- After completing the above steps, if the stack is empty, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.