Given a string S of size N consisting of only ‘(‘ and ‘)’ only and a positive integer K, the task is to check if the given string can be made a valid parenthesis sequence by moving any characters of the string S to either end of the string at most K number of times.
Input: S = “)(“, K = 1
Explanation: Move S to the end of the string.
Now, the modified string S is “()” which is balanced. Therefore, the number of moves required is 1( = K).
Input: S = “()()”, K = 0
Approach: The given problem can be solved based on the following observations:
- If N is odd or the count of opening and closing brackets are not equal, then it is not possible to make a valid parenthesis sequence.
- The idea is to traverse the given sequence and keep track of the difference of count of opening and closing brackets, and if the difference becomes negative at any index, then move some opening bracket after the current index and move it to the beginning.
Follow the steps below to solve the problem:
- If N is odd or the count of opening and closing brackets are not equal, then it is not possible to make a valid parenthesis sequence. Hence, print “No”. Otherwise, perform the following steps:
- Initialize two variables, say count and ans as 0 that keeps track of the difference of opening and closing brackets and the required number of moves respectively.
- Traverse the given string S and perform the following steps:
- If the current character S[i] is ‘(‘, then increment the value of count by 1.
- Otherwise, decrement the value of count by 1.
- If the count is less than 0, then update the count to 0, and increment the value of ans by 1.
- After completing the above steps, if the value of ans is at most K, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.