Find an equal point in a string of brackets - GeeksforGeeks

22 Apr, 2022
Given a string of brackets, the task is to find an index k which decides the number of opening brackets is equal to the number of closing brackets. The string must be consists of only opening and closing brackets i.e. ‘(‘ and ‘)’.
An equal point is an index such that the number of opening brackets before it is equal to the number of closing brackets from and after.
Examples:  
Input: str = “(())))(“Output:   4Explanation: After index 4, string splits into (()) and ))(. The number of opening brackets in the first part is equal to the number of closing brackets in the second part.
Input: str = “))”Output: 2Explanation: As after 2nd position i.e. )) and “empty” string will be split into these two parts. So, in this number of opening brackets i.e. 0 in the first part is equal to the number of closing brackets in the second part i.e. also 0.
 
Asked in: Amazon 
Approach 1:
Store the number of opening brackets appears in the string up to every index, it must start from starting index.
Similarly, Store the number of closing brackets appears in the string upto each and every index but it should be done from last index.
Check if any index has the same value of opening and closing brackets.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets#include<bits/stdc++.h>using namespace std; // Function to find an equal indexint findIndex(string str){    int len = str.length();    int open[len+1], close[len+1];    int index = -1;    memset(open, 0, sizeof (open));    memset(close, 0, sizeof (close));     open[0] = 0;    close[len] = 0;    if (str[0]=='(')        open[1] = 1;    if (str[len-1] == ')')        close[len-1] = 1;     // Store the number of opening brackets    // at each index    for (int i = 1; i < len; i++)    {        if ( str[i] == '(' )            open[i+1] = open[i] + 1;        else            open[i+1] = open[i];    }     // Store the number of closing brackets    // at each index    for (int i = len-2; i >= 0; i--)    {        if ( str[i] == ')' )            close[i] = close[i+1] + 1;        else            close[i] = close[i+1];    }     // check if there is no opening or closing    // brackets    if (open[len] == 0)        return len;    if (close[0] == 0)        return 0;     // check if there is any index at which    // both brackets are equal    for (int i=0; i<=len; i++)        if (open[i] == close[i])            index = i;     return index;} // Driver codeint main(){    string str = "(()))(()()())))";    cout << findIndex(str);    return 0;}
// Java program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets public class GFG{    // Method to find an equal index    static int findIndex(String str)    {        int len = str.length();        int open[] = new int[len+1];        int    close[] = new int[len+1];        int index = -1;              open[0] = 0;        close[len] = 0;        if (str.charAt(0)=='(')            open[1] = 1;        if (str.charAt(len-1) == ')')            close[len-1] = 1;              // Store the number of opening brackets        // at each index        for (int i = 1; i < len; i++)        {            if ( str.charAt(i) == '(' )                open[i+1] = open[i] + 1;            else                open[i+1] = open[i];        }              // Store the number of closing brackets        // at each index        for (int i = len-2; i >= 0; i--)        {            if ( str.charAt(i) == ')' )                close[i] = close[i+1] + 1;            else                close[i] = close[i+1];        }              // check if there is no opening or closing        // brackets        if (open[len] == 0)            return len;        if (close[0] == 0)            return 0;             // check if there is any index at which        // both brackets are equal        for (int i=0; i<=len; i++)            if (open[i] == close[i])                index = i;              return index;    }         // Driver Method    public static void main(String[] args)    {        String str = "(()))(()()())))";        System.out.println(findIndex(str));    }}
# Method to find an equal indexdef findIndex(str):    l = len(str)    open = [0] * (l + 1)    close = [0] * (l + 1)    index = -1         open[0] = 0    close[l] = 0    if (str[0]=='('):        open[1] = 1    if (str[l - 1] == ')'):        close[l - 1] = 1         # Store the number of    # opening brackets    # at each index    for i in range(1, l):        if (str[i] == '('):            open[i + 1] = open[i] + 1        else:            open[i + 1] = open[i]         # Store the number    # of closing brackets    # at each index    for i in range(l - 2, -1, -1):        if ( str[i] == ')'):            close[i] = close[i + 1] + 1        else:            close[i] = close[i + 1]         # check if there is no    # opening or closing brackets    if (open[l] == 0):        return len    if (close[0] == 0):        return 0         # check if there is any    # index at which both    # brackets are equal    for i in range(l + 1):        if (open[i] == close[i]):            index = i         return index     # Driver Codestr = "(()))(()()())))"print(findIndex(str)) # This code is contributed# by ChitraNayal
// C# program to find an index// k which decides the number// of opening brackets is equal// to the number of closing bracketsusing System; class GFG{// Method to find an equal indexstatic int findIndex(string str){    int len = str.Length;    int[] open = new int[len + 1];    int[] close = new int[len + 1];    int index = -1;     open[0] = 0;    close[len] = 0;    if (str[0] == '(')        open[1] = 1;    if (str[len - 1] == ')')        close[len - 1] = 1;     // Store the number of    // opening brackets    // at each index    for (int i = 1; i < len; i++)    {        if (str[i] == '(')            open[i + 1] = open[i] + 1;        else            open[i + 1] = open[i];    }     // Store the number    // of closing brackets    // at each index    for (int i = len - 2; i >= 0; i--)    {        if (str[i] == ')')            close[i] = close[i + 1] + 1;        else            close[i] = close[i + 1];    }     // check if there is no    // opening or closing    // brackets    if (open[len] == 0)        return len;    if (close[0] == 0)        return 0;     // check if there is any    // index at which both    // brackets are equal    for (int i = 0; i <= len; i++)        if (open[i] == close[i])            index = i;     return index;} // Driver Codepublic static void Main(){    string str = "(()))(()()())))";    Console.Write(findIndex(str));}} // This code is contributed// by ChitraNayal
<?php// Method to find an equal indexfunction findIndex($str){    $len = strlen($str);    $open = array(0, $len + 1, NULL);    $close = array(0, $len + 1, NULL);    $index = -1;         $open[0] = 0;    $close[$len] = 0;    if ($str[0] == '(')    $open[1] = 1;    if ($str[$len - 1] == ')')    $close[$len - 1] = 1;         // Store the number    // of opening brackets    // at each index    for ($i = 1; $i < $len; $i++)    {        if ($str[$i] == '(')            $open[$i + 1] = $open[$i] + 1;        else            $open[$i + 1] = $open[$i];    }         // Store the number    // of closing brackets    // at each index    for ($i = $len - 2; $i >= 0; $i--)    {        if ($str[$i] == ')')        $close[$i] = $close[$i + 1] + 1;        else        $close[$i] = $close[$i + 1];    }         // check if there is no    // opening or closing    // brackets    if ($open[$len] == 0)        return $len;    if ($close[0] == 0)        return 0;         // check if there is any    // index at which both    // brackets are equal    for ($i = 0; $i <= $len; $i++)        if ($open[$i] == $close[$i])            $index = $i;         return $index;}     // Driver Code$str = "(()))(()()())))";echo (findIndex($str)); // This code is contributed// by ChitraNayal?>
<script> // Javascript program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets     // Method to find an equal indexfunction findIndex(str){    let len = str.length;    let open = new Array(len + 1);    let close = new Array(len + 1);    for(let i = 0; i < len + 1; i++)    {        open[i] = 0;        close[i] = 0;    }    let index = -1;        open[0] = 0;    close[len] = 0;         if (str[0] == '(')        open[1] = 1;    if (str[len - 1] == ')')        close[len - 1] = 1;        // Store the number of opening brackets    // at each index    for(let i = 1; i < len; i++)    {        if (str[i] == '(')            open[i + 1] = open[i] + 1;        else            open[i + 1] = open[i];    }        // Store the number of closing brackets    // at each index    for(let i = len - 2; i >= 0; i--)    {        if (str[i] == ')')            close[i] = close[i + 1] + 1;        else            close[i] = close[i + 1];    }        // Check if there is no opening or closing    // brackets    if (open[len] == 0)        return len;    if (close[0] == 0)        return 0;       // Check if there is any index at which    // both brackets are equal    for(let i = 0; i <= len; i++)        if (open[i] == close[i])            index = i;        return index;} // Driver Codelet str = "(()))(()()())))"; document.write(findIndex(str)); // This code is contributed by avanitrachhadiya2155 </script>
9
Time Complexity: O(N), where N is the size of given stringAuxiliary Space: O(N)
Approach 2: 
Count the total number of closed brackets in string and store in variable, let’s say cnt_close.
So count of open brackets is length of (string – count) of closed brackets.
Traverse string again but now keep count of open brackets in string, let’s say cnt_open.
Now while traversing, let index be i, so count of closed brackets till that index will be (i+1 – cnt_open).
Hence, we can check for what index, the count of open brackets in first part equals that of count of closed brackets in second part.
Equation becomes cnt_close – (i+1 – cnt_open) = cnt_open, we have to find i.
After evaluating above equation we can see cnt_open gets cancelled on both sides so no need.
C++
Java
Python3
Javascript
PHP
// C++ program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets#include <bits/stdc++.h>using namespace std; // Function to find an equal indexint findIndex(string str){    // STL to count occurrences of ')'    int cnt_close = count(str.begin(), str.end(), ')');    for (int i = 0; str[i] != '\0'; i++)        if (cnt_close == i)            return i;    // If no opening brackets    return str.size();} // Driver codeint main(){    string str = "(()))(()()())))";    cout << findIndex(str);    return 0;} // This code is contributed by Dhananjay Dhawale @chessnoobdj
// Java program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets public class GFG {    // Method to find an equal index    static int findIndex(String str)    {        int len = str.length();        int cnt_close = 0;        for (int i = 0; i < len; i++)            if (str.charAt(i) == ')')                cnt_close++;        for (int i = 0; i < len; i++)            if (cnt_close == i)                return i;        // If no opening brackets        return len;    }     // Driver Method    public static void main(String[] args)    {        String str = "(()))(()()())))";        System.out.println(findIndex(str));    }} // This code is contributed by Aditya Kumar (adityakumar129)
# Method to find an equal indexdef findIndex(str):    cnt_close = 0    l = len(str)    for i in range(1, l):        if(str[i] == ')'):            cnt_close = cnt_close + 1     for i in range(1, l):        if(cnt_close == i):            return i    # If no opening brackets    return l  # Driver Codestr = "(()))(()()())))"print(findIndex(str)) # This code is contributed by Aditya Kumar (adityakumar129)
<script> // Javascript program to find an index k which// decides the number of opening brackets// is equal to the number of closing brackets     // Method to find an equal indexfunction findIndex(str){    let len = str.length;    int cnt_close = 0;    for(let i = 0; i < len; i++)        if (str[i] == ')')            cnt_close++;               for(let i = 0; i < len; i++)         if (cnt_close == i)            return i;        // If no opening brackets        return len;     // Driver Codelet str = "(()))(()()())))"; document.write(findIndex(str)); // This code is contributed by Aditya Kumar (adityakumar129) </script>
<?php// Method to find an equal indexfunction findIndex($str){    $len = strlen($str);    $cnt_close = 0;      for ($i = 1; $i < $len; $i++)        if ($str[$i] == ')')            $cnt_close ++;             for ($i = 1; $i < $len; $i++)        if ($cnt_close == $i)              return $i;      return $len;}     // Driver Code$str = "(()))(()()())))";echo (findIndex($str)); // This code is contributed by Aditya Kumar (adityakumar129)?>
9
Time Complexity: O(N), Where N is the size of given stringAuxiliary Space: O(1)
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
Shravankashyap2
avanitrachhadiya2155
chessnoobdj
adityakumar129
harendrakumar123
rkbhola5
Amazon
Arrays
Strings
Amazon
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack