Java Stack in Java : Hacker Rank Solution : Digit Wood


A string containing only parentheses is balanced if the following is true: 1. if it is an empty string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A} and [A] are also correct.

Examples of some correctly balanced strings are: “{}()”, “[{()}]”, “({()})”

Examples of some unbalanced strings are: “{}(“, “({)}”, “[[“, “}{” etc.

Given a string, determine if it is balanced or not.

Input Format

There will be multiple lines in the input file, each having a single non-empty string. You should read input till end-of-file.

The part of the code that handles input operation is already provided in the editor.

Output Format

For each case, print ‘true’ if the string is balanced, ‘false’ otherwise.

Sample Input

Sample Output


SOLUTION : – To optimize the given code, you can make a few changes:

  1. 1. Use a Stack<Character> instead of Stack<String> since you are dealing with single characters.
  2. 2. Instead of using String.split("") to split the input into characters, you can directly iterate over the characters of the input string using charAt(i).
  3. 3. Use a more descriptive variable name instead of Symbol for the stack.

Here’s the optimized version of the code:


Leave a Reply

Your email address will not be published. Required fields are marked *