Count all indices of cyclic regular parenthesis
Last Updated :
19 Apr, 2021
Given a string S of length N, consisting of only opening '(' and closing ')' parenthesis. The task is to find all indices 'K' such that S[K...N-1] + S[0...K-1] is a regular parenthesis.
A regular parentheses string is either empty (""), "(" + str1 + ")", or str1 + str2, where str1 and str2 are regular parentheses strings.
For example: "", "()", "(())()", and "(()(()))" are regular parentheses strings.
Examples:
Input: str = ")()("
Output: 2
Explanation:
For K = 1, S = ()(), which is regular.
For K = 3, S = ()(), which is regular.
Input: S = "())("
Output: 1
Explanation:
For K = 3, S = (()), which is regular.
Naive Approach: The naive approach is to split the given string str at every possible index(say K) and check whether str[K, N-1] + str[0, K-1] is palindromic or not. If yes then print that particular value of K.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The idea is to observe that if at any index(say K) where the count of closing brackets is greater than the count of opening brackets then that index is the possible index of splitting the string. Below are the steps:
- The partition is only possible when the count the number of opening brackets must be equal to the number of closing brackets. Else we can't form any partition to balanced the parenthesis.
- Create an auxiliary array(say aux[]) of size length of the string.
- Traverse the given string if character at any index(say i) is '(' then update aux[i] to 1 else update strong>aux[i] to -1.
- The frequency of the minimum element in the above auxiliary array is the required number of splitting(say at index K) to make S[K...N-1] + S[0...K-1] a regular parenthesis string.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find all indices which
// cyclic shift leads to get
// balanced parenthesis
int countCyclicShifts(string& S, int n)
{
int aux[n] = { 0 };
// Create auxiliary array
for (int i = 0; i < n; ++i) {
if (S[i] == '(')
aux[i] = 1;
else
aux[i] = -1;
}
// Finding prefix sum and
// minimum element
int mn = aux[0];
for (int i = 1; i < n; ++i) {
aux[i] += aux[i - 1];
// Update the minimum element
mn = min(mn, aux[i]);
}
// ChecK if count of '(' and
// ')' are equal
if (aux[n - 1] != 0)
return 0;
// Find count of minimum
// element
int count = 0;
// Find the frequency of mn
for (int i = 0; i < n; ++i) {
if (aux[i] == mn)
count++;
}
// Return the count
return count;
}
// Driver Code
int main()
{
// Given string S
string S = ")()(";
int N = S.length();
// Function Call
cout << countCyclicShifts(S, N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// Function to find all indices which
// cyclic shift leads to get
// balanced parenthesis
static int countCyclicShifts(String S, int n)
{
// Create auxiliary array
int[] aux = new int[n];
for(int i = 0; i < n; ++i)
{
if (S.charAt(i) == '(')
aux[i] = 1;
else
aux[i] = -1;
}
// Finding prefix sum and
// minimum element
int mn = aux[0];
for(int i = 1; i < n; ++i)
{
aux[i] += aux[i - 1];
// Update the minimum element
mn = Math.min(mn, aux[i]);
}
// Check if count of '(' and ')'
// are equal
if (aux[n - 1] != 0)
return 0;
// Find count of minimum
// element
int count = 0;
// Find the frequency of mn
for(int i = 0; i < n; ++i)
{
if (aux[i] == mn)
count++;
}
// Return the count
return count;
}
// Driver code
public static void main(String[] args)
{
// Given string S
String S = ")()(";
// length of the string S
int N = S.length();
System.out.print(countCyclicShifts(S, N));
}
}
// This code is contributed by sanjoy_62
Python3
# Python3 program for the above approach
# Function to find all indices which
# cyclic shift leads to get
# balanced parenthesis
def countCyclicShifts(S, n):
aux = [0 for i in range(n)]
# Create auxiliary array
for i in range(0, n):
if (S[i] == '('):
aux[i] = 1
else:
aux[i] = -1
# Finding prefix sum and
# minimum element
mn = aux[0]
for i in range(1, n):
aux[i] += aux[i - 1]
# Update the minimum element
mn = min(mn, aux[i])
# ChecK if count of '(' and
# ')' are equal
if (aux[n - 1] != 0):
return 0
# Find count of minimum
# element
count = 0
# Find the frequency of mn
for i in range(0, n):
if (aux[i] == mn):
count += 1
# Return the count
return count
# Driver Code
# Given string S
S = ")()("
N = len(S)
# Function call
print(countCyclicShifts(S, N))
# This code is contributed by Sanjit_Prasad
C#
// C# program for the above approach
using System;
class GFG{
// Function to find all indices which
// cyclic shift leads to get
// balanced parenthesis
static int countCyclicShifts(string S, int n)
{
// Create auxiliary array
int[] aux = new int[n];
for(int i = 0; i < n; ++i)
{
if (S[i] == '(')
aux[i] = 1;
else
aux[i] = -1;
}
// Finding prefix sum and
// minimum element
int mn = aux[0];
for(int i = 1; i < n; ++i)
{
aux[i] += aux[i - 1];
// Update the minimum element
mn = Math.Min(mn, aux[i]);
}
// Check if count of '(' and ')'
// are equal
if (aux[n - 1] != 0)
return 0;
// Find count of minimum
// element
int count = 0;
// Find the frequency of mn
for(int i = 0; i < n; ++i)
{
if (aux[i] == mn)
count++;
}
// Return the count
return count;
}
// Driver code
public static void Main(string[] args)
{
// Given string S
string S = ")()(";
// length of the string S
int N = S.Length;
Console.Write(countCyclicShifts(S, N));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript Program to implement
// the above approach
// Function to find all indices which
// cyclic shift leads to get
// balanced parenthesis
function countCyclicShifts(S, n)
{
// Create auxiliary array
let aux = [];
for(let i = 0; i < n; ++i)
{
if (S[i] == '(')
aux[i] = 1;
else
aux[i] = -1;
}
// Finding prefix sum and
// minimum element
let mn = aux[0];
for(let i = 1; i < n; ++i)
{
aux[i] += aux[i - 1];
// Update the minimum element
mn = Math.min(mn, aux[i]);
}
// Check if count of '(' and ')'
// are equal
if (aux[n - 1] != 0)
return 0;
// Find count of minimum
// element
let count = 0;
// Find the frequency of mn
for(let i = 0; i < n; ++i)
{
if (aux[i] == mn)
count++;
}
// Return the count
return count;
}
// Driver Code
// Given string S
let S = ")()(";
// length of the string S
let N = S.length;
document.write(countCyclicShifts(S, N));
// This code is contributed by avijitmondal1998.
</script>
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(N), where N is the length of the string.
Similar Reads
Mastering Bracket Problems for Competitive Programming Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec
4 min read
Check for balanced with only one type of brackets Given a string str of length N, consisting of '(' and ')' only, the task is to check whether it is balanced or not.Examples:Input: str = "((()))()()" Output: BalancedInput: str = "())((())" Output: Not Balanced Approach 1: Declare a Flag variable which denotes expression is balanced or not.Initialis
9 min read
Valid Parentheses in an Expression Given a string s representing an expression containing various types of brackets: {}, (), and [], the task is to determine whether the brackets in the expression are balanced or not. A balanced expression is one where every opening bracket has a corresponding closing bracket in the correct order.Exa
8 min read
Length of longest balanced parentheses prefix Given a string of open bracket '(' and closed bracket ')'. The task is to find the length of longest balanced prefix. Examples: Input : S = "((()())())((" Output : 10From index 0 to index 9, they are forming a balanced parentheses prefix.Input : S = "()(())((()"Output : 6The idea is take value of op
9 min read
Modify a numeric string to a balanced parentheses by replacements Given a numeric string S made up of characters '1', '2' and '3' only, the task is to replace characters with either an open bracket ( '(' ) or a closed bracket ( ')' ) such that the newly formed string becomes a balanced bracket sequence. Note: All occurrences of a character must be replaced by the
10 min read
Check if the bracket sequence can be balanced with at most one change in the position of a bracket Given an unbalanced bracket sequence as a string str, the task is to find whether the given string can be balanced by moving at most one bracket from its original place in the sequence to any other position.Examples: Input: str = ")(()" Output: Yes As by moving s[0] to the end will make it valid. "(
6 min read
Number of closing brackets needed to complete a regular bracket sequence Given an incomplete bracket sequence S. The task is to find the number of closing brackets ')' needed to make it a regular bracket sequence and print the complete bracket sequence. You are allowed to add the brackets only at the end of the given bracket sequence. If it is not possible to complete th
7 min read
Minimum number of Parentheses to be added to make it valid Given a string S of parentheses '(' or ')' where, 0\leq len(S)\leq 1000 . The task is to find a minimum number of parentheses '(' or ')' (at any positions) we must add to make the resulting parentheses string is valid. Examples: Input: str = "())" Output: 1 One '(' is required at beginning. Input: s
9 min read
Minimum bracket reversals to make an expression balanced Given an expression with only '}' and '{'. The expression may not be balanced. Find minimum number of bracket reversals to make the expression balanced.Examples: Input: s = "}{{}}{{{"Output: 3Explanation: We need to reverse minimum 3 brackets to make "{{{}}{}}". Input: s = "{{"Output: 1Explanation:
15+ min read
Find the number of valid parentheses expressions of given length Given a number n, the task is to find the number of valid parentheses expressions of that length. Examples : Input: 2Output: 1 Explanation: There is only possible valid expression of length 2, "()"Input: 4Output: 2 Explanation: Possible valid expression of length 4 are "(())" and "()()" Input: 6Outp
11 min read