Bird
Raised Fist0
DSA Javaprogramming~30 mins

Balanced Parentheses Problem Using Stack in DSA Java - Build from Scratch

Choose your learning style10 modes available
Balanced Parentheses Problem Using Stack
📖 Scenario: Imagine you are building a simple code editor that checks if the parentheses in a line of code are balanced. Balanced parentheses mean every opening bracket has a matching closing bracket in the correct order.
🎯 Goal: You will create a Java program that uses a stack to check if a given string of parentheses is balanced or not.
📋 What You'll Learn
Create a string variable with a specific parentheses sequence
Create a stack to help check parentheses
Write logic to check if the parentheses are balanced using the stack
Print Balanced if parentheses match, otherwise print Not Balanced
💡 Why This Matters
🌍 Real World
Checking balanced parentheses is important in code editors, compilers, and calculators to ensure expressions are correct.
💼 Career
Understanding stacks and balanced parentheses is a common interview question and helps in debugging and writing parsers.
Progress0 / 4 steps
1
Create the parentheses string
Create a String variable called parentheses and set it to the exact value "(()[])".
DSA Java
Hint

Use String parentheses = "(()[])"; to store the parentheses sequence.

2
Create a stack to hold characters
Add a Stack<Character> called stack using new Stack<>() inside the main method after the parentheses variable.
DSA Java
Hint

Use Stack<Character> stack = new Stack<>(); to create the stack.

3
Check if parentheses are balanced using the stack
Write a for loop using int i = 0; i < parentheses.length(); i++ to iterate over parentheses.charAt(i). Inside the loop, push opening brackets '(', '[', '{' onto stack. For closing brackets ')', ']', '}', check if stack is empty or top does not match the correct opening bracket, then print Not Balanced and return. After the loop, if stack is empty, print Balanced, else print Not Balanced.
DSA Java
Hint

Use a loop to check each character. Push opening brackets. For closing brackets, pop and check if matching. Print result accordingly.

4
Print the result
Run the program and ensure it prints Balanced for the given parentheses string.
DSA Java
Hint

Run the program to check if it prints Balanced for the input string.

Practice

(1/5)
1. What does the Balanced Parentheses problem using a stack check for in a string?
easy
A. Whether every opening bracket has a matching closing bracket in correct order
B. If the string contains only alphabets
C. If the string length is even
D. Whether the string contains any digits

Solution

  1. Step 1: Understand the problem goal

    The Balanced Parentheses problem checks if all opening brackets like '(' have a matching closing bracket ')' in the correct order.
  2. Step 2: Role of stack in checking

    A stack helps track opening brackets and ensures each is closed properly in sequence.
  3. Final Answer:

    Whether every opening bracket has a matching closing bracket in correct order -> Option A
  4. Quick Check:

    Balanced parentheses = matching pairs [OK]
Hint: Match each '(' with ')' using stack push/pop [OK]
Common Mistakes:
  • Thinking it checks string length
  • Ignoring order of brackets
  • Checking only for digits or alphabets
2. Which of the following Java code snippets correctly initializes a stack to check balanced parentheses?
easy
A. Stack<Character> stack = new Stack<>();
B. Stack stack = new Stack<Character>();
C. Stack<Character> stack = Stack();
D. Stack<Character> stack = new Stack<Character>;

Solution

  1. Step 1: Check correct Stack initialization syntax

    In Java, to create a stack of Characters, use: Stack<Character> stack = new Stack<>(); which uses diamond operator for type inference.
  2. Step 2: Identify errors in other options

    Stack stack = new Stack<Character>(); misses generic type on right side; Stack<Character> stack = Stack(); misses 'new' keyword; Stack<Character> stack = new Stack<Character>; misses parentheses after constructor.
  3. Final Answer:

    Stack<Character> stack = new Stack<>(); -> Option A
  4. Quick Check:

    Correct Java stack init = Stack<Character> stack = new Stack<>(); [OK]
Hint: Use diamond operator <> with new Stack<>() [OK]
Common Mistakes:
  • Omitting 'new' keyword
  • Missing parentheses after constructor
  • Incorrect generic type syntax
3. What will be the output of the following Java code snippet?
String s = "({[]})";
System.out.println(isBalanced(s));

public static boolean isBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    for (char c : s.toCharArray()) {
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c);
        } else {
            if (stack.isEmpty()) return false;
            char top = stack.pop();
            if ((c == ')' && top != '(') ||
                (c == '}' && top != '{') ||
                (c == ']' && top != '[')) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}
medium
A. Compilation error
B. false
C. true
D. Runtime exception

Solution

  1. Step 1: Trace the input string "({[]})" character by character

    Push '(' '{' '[' onto stack; then pop matching pairs for ']' '}' ')'. Stack ends empty.
  2. Step 2: Check final stack state

    Stack is empty after processing all characters, so return true.
  3. Final Answer:

    true -> Option C
  4. Quick Check:

    All brackets matched = true [OK]
Hint: Stack empty at end means balanced [OK]
Common Mistakes:
  • Not checking stack empty at end
  • Mismatching brackets order
  • Ignoring empty stack before pop
4. Identify the error in this Java method for checking balanced parentheses:
public static boolean checkBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    for (char c : s.toCharArray()) {
        if (c == '(' || c == '{' || c == '[') {
            stack.push(c);
        } else {
            char top = stack.pop();
            if ((c == ')' && top != '(') ||
                (c == '}' && top != '{') ||
                (c == ']' && top != '[')) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}
medium
A. For loop syntax is incorrect
B. Wrong comparison operators used
C. Stack should store Strings not Characters
D. Missing check if stack is empty before pop

Solution

  1. Step 1: Analyze stack pop operation

    Pop is called without checking if stack is empty, which can cause runtime exception if closing bracket appears first.
  2. Step 2: Identify missing empty check

    Must check stack.isEmpty() before pop to avoid EmptyStackException.
  3. Final Answer:

    Missing check if stack is empty before pop -> Option D
  4. Quick Check:

    Always check stack empty before pop [OK]
Hint: Check stack empty before pop to avoid errors [OK]
Common Mistakes:
  • Ignoring empty stack before pop
  • Assuming input always starts with opening bracket
  • Not handling runtime exceptions
5. Given the string "[{()}]({[]})", which of the following modifications to the balanced parentheses algorithm will correctly handle this input and return true?
hard
A. Use two stacks, one for opening and one for closing brackets separately
B. Use a stack and check matching pairs for all bracket types, ensuring stack is empty at end
C. Only check if the string length is even and contains brackets
D. Ignore curly braces '{}' and only check parentheses '()'

Solution

  1. Step 1: Understand input complexity

    The string contains multiple types of brackets nested and sequentially combined.
  2. Step 2: Apply stack-based matching for all bracket types

    Push opening brackets, pop and match closing brackets; ensure stack empty at end for balanced check.
  3. Step 3: Evaluate other options

    Length check or ignoring bracket types will fail; two stacks unnecessary and incorrect.
  4. Final Answer:

    Use a stack and check matching pairs for all bracket types, ensuring stack is empty at end -> Option B
  5. Quick Check:

    Stack matching all brackets = true [OK]
Hint: Match all bracket types with one stack, check empty at end [OK]
Common Mistakes:
  • Ignoring some bracket types
  • Relying on string length only
  • Using multiple stacks unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard