Javatpoint Logo
Javatpoint Logo

Balanced Parentheses in Java

The balanced parentheses problem is one of the common programming problems that is also known as Balanced brackets. This problem is commonly asked by the interviewers where we have to validate whether the brackets in a given string are balanced on not.

Characters such as "(", ")", "[", "]", "{", and "}" are considered brackets.

A collection of parentheses is considered to be a matched pair if the opening bracket occurs to the left of the corresponding closing bracket respectively.

If the brackets enclosed in a string are not matched, bracket pairs are not balanced.

In the same way, a string having non-bracket characters such as a-z, A-Z, 0-9 and other special characters such as #, $, and @ is also considered to be unbalanced.

Balanced Parentheses in Java

Example "{[(])}"

It is an unbalanced input string because the pair of round brackets, "()", encloses a single unbalanced closing square bracket, "]", and the pair of square brackets, "[]", encloses a single unbalanced opening round bracket, "(".

A string having brackets is said to be balanced if:

  • A matching closing bracket occurs to the right of each corresponding opening bracket.
  • Brackets enclosed within balanced brackets should also be balanced
  • It should not contain any non-bracket character.

Note 1: Null is considered to be balanced.

Note 2: Empty string is considered to be balanced.

Algorithm (Deque)

  1. First, we declare a character stack.
  2. Convert input string into a character array.
  3. Traverse the input string(By traversing the character array).
    1. We push the current character to stack if it is a starting bracket('(' or '{' or '[').
    2. We pop the current character from the stack if it is a closing bracket. If the popped character doesn't match with the starting bracket, brackets are not balanced.
  4. Once the traversing is finished and there are some starting brackets left in the stack, the brackets are not balanced.

We can implement the code for balanced parentheses by using simple for loop, Deque and stack.


Balanced Parentheses in Java


Balanced Parentheses in Java


Balanced Parentheses in Java

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA