Related Articles

# Identify and mark unmatched parenthesis in an expression

• Difficulty Level : Easy
• Last Updated : 18 Sep, 2020

Given an expression, find and mark matched and unmatched parenthesis in it. We need to replace all balanced opening parenthesis with 0, balanced closing parenthesis with 1, and all unbalanced with -1.
Examples:

```Input : ((a)
Output : -10a1

Input : (a))
Output : 0a1-1

Input  : (((abc))((d)))))
Output : 000abc1100d111-1-1

```

The idea is based on a stack. We run a loop from the start of the string Up to end and for every ‘(‘, we push it into a stack. If the stack is empty, and we encounter a closing bracket ‘)’ we replace -1 at that index of the string. Else we replace all opening brackets ‘(‘ with 0 and closing brackets with 1. Then pop from the stack.

## C++

 `// CPP program to mark balanced and unbalanced``// parenthesis.``#include ``using` `namespace` `std;` `void` `identifyParenthesis(string a)``{``    ``stack<``int``> st;` `    ``// run the loop upto end of the string``    ``for` `(``int` `i = 0; i < a.length(); i++) {` `        ``// if a[i] is opening bracket then push``        ``// into stack``        ``if` `(a[i] == ``'('``)``            ``st.push(i);``        ` `        ``// if a[i] is closing bracket ')'``        ``else` `if` `(a[i] == ``')'``) {` `            ``// If this closing bracket is unmatched``            ``if` `(st.empty())``                ``a.replace(i, 1, ``"-1"``);``            ` `            ``else` `{` `                ``// replace all opening brackets with 0``                ``// and closing brackets with 1``                ``a.replace(i, 1, ``"1"``);``                ``a.replace(st.top(), 1, ``"0"``);``                ``st.pop();``            ``}``        ``}``    ``}` `    ``// if stack is not empty then pop out all``    ``// elements from it and replace -1 at that``    ``// index of the string``    ``while` `(!st.empty()) {``        ``a.replace(st.top(), 1, ``"-1"``);``        ``st.pop();``    ``}` `    ``// print final string``    ``cout << a << endl;``}` `// Driver code``int` `main()``{``    ``string str = ``"(a))"``;``    ``identifyParenthesis(str);``    ``return` `0;``}`

## Java

 `// Java program to mark balanced and``// unbalanced parenthesis.``import` `java.util.*;` `class` `GFG``{``static` `void` `identifyParenthesis(StringBuffer a)``{``    ``Stack st = ``new` `Stack();` `    ``// run the loop upto end of the string``    ``for` `(``int` `i = ``0``; i < a.length(); i++)``    ``{` `        ``// if a[i] is opening bracket then push``        ``// into stack``        ``if` `(a.charAt(i) == ``'('``)``            ``st.push(i);``        ` `        ``// if a[i] is closing bracket ')'``        ``else` `if` `(a.charAt(i) == ``')'``)``        ``{` `            ``// If this closing bracket is unmatched``            ``if` `(st.empty())``                ``a.replace(i, i + ``1``, ``"-1"``);``            ` `            ``else``            ``{` `                ``// replace all opening brackets with 0``                ``// and closing brackets with 1``                ``a.replace(i, i + ``1``, ``"1"``);``                ``a.replace(st.peek(), st.peek() + ``1``, ``"0"``);``                ``st.pop();``            ``}``        ``}``    ``}` `    ``// if stack is not empty then pop out all``    ``// elements from it and replace -1 at that``    ``// index of the string``    ``while` `(!st.empty())``    ``{``        ``a.replace(st.peek(), ``1``, ``"-1"``);``        ``st.pop();``    ``}` `    ``// print final string``    ``System.out.println(a);``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``StringBuffer str = ``new` `StringBuffer(``"(a))"``);``    ``identifyParenthesis(str);``}``}` `// This code is contributed by Princi Singh`

## Python3

 `# Python3 program to``# mark balanced and``# unbalanced parenthesis.``def` `identifyParenthesis(a):``    ``st ``=` `[]` `    ``# run the loop upto``    ``# end of the string``    ``for` `i ``in` `range` `(``len``(a)):` `        ``# if a[i] is opening``        ``# bracket then push``        ``# into stack``        ``if` `(a[i] ``=``=` `'('``):``            ``st.append(a[i])``        ` `        ``# if a[i] is closing bracket ')'``        ``elif` `(a[i] ``=``=` `')'``):` `            ``# If this closing bracket``            ``# is unmatched``            ``if` `(``len``(st) ``=``=` `0``):``                ``a ``=` `a.replace(a[i], ``"-1"``, ``1``)``            ` `            ``else``:` `                ``# replace all opening brackets with 0``                ``# and closing brackets with 1``                ``a ``=` `a.replace(a[i], ``"1"``, ``1``)``                ``a ``=` `a.replace(st[``-``1``], ``"0"``, ``1``)``                ``st.pop()``          ` `    ``# if stack is not empty``    ``# then pop out all``    ``# elements from it and``    ``# replace -1 at that``    ``# index of the string``    ``while` `(``len``(st) !``=` `0``):``        ``a ``=` `a.replace(st[``-``1``], ``1``, ``"-1"``);``        ``st.pop()` `    ``# print final string``    ``print``(a)` `# Driver code``if` `__name__ ``=``=` `"__main__"``:` `    ``st ``=` `"(a))"``    ``identifyParenthesis(st)``    ` `# This code is contributed by Chitranayal`

Output:

```0a1-1

```

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.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up