Bird
Raised Fist0
DSA Javaprogramming~20 mins

Balanced Parentheses Problem Using Stack in DSA Java - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Balanced Parentheses Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Balanced Parentheses Check
What is the output of the following Java code that checks if the parentheses in the string are balanced?
DSA Java
import java.util.Stack;

public class BalancedParentheses {
    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else if (c == ')') {
                if (stack.isEmpty()) {
                    return false;
                }
                stack.pop();
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("(()())"));
    }
}
Atrue
BCompilation error
Cfalse
DRuntime exception
Attempts:
2 left
💡 Hint
Think about how the stack is used to match opening and closing parentheses.
❓ Predict Output
intermediate
2:00remaining
Output for Unbalanced Parentheses
What will be the output of the following code snippet when checking the string "(()" for balanced parentheses?
DSA Java
import java.util.Stack;

public class BalancedParentheses {
    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else if (c == ')') {
                if (stack.isEmpty()) {
                    return false;
                }
                stack.pop();
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("(()"));
    }
}
ACompilation error
Btrue
Cfalse
DRuntime exception
Attempts:
2 left
💡 Hint
Check if all opening parentheses have matching closing ones.
🔧 Debug
advanced
2:00remaining
Identify the Error in Parentheses Checking Code
What error will the following code produce when run with input ")("?
DSA Java
import java.util.Stack;

public class BalancedParentheses {
    public static boolean isBalanced(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(') {
                stack.push(c);
            } else if (c == ')') {
                if (stack.isEmpty()) {
                    return false;
                }
                stack.pop();
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced(")("));
    }
}
AReturns false
BReturns true
CCompilation error
DEmptyStackException at runtime
Attempts:
2 left
💡 Hint
Consider what happens when popping from an empty stack.
🧠 Conceptual
advanced
1:30remaining
Why Use Stack for Balanced Parentheses?
Why is a stack the best data structure to check for balanced parentheses?
ABecause it automatically counts the number of parentheses
BBecause it stores all characters in sorted order
CBecause it uses less memory than arrays
DBecause it allows checking pairs in last-in, first-out order which matches nested parentheses structure
Attempts:
2 left
💡 Hint
Think about how parentheses open and close in nested order.
🚀 Application
expert
2:30remaining
Output of Balanced Parentheses with Multiple Types
What is the output of the following Java code that checks if the string has balanced parentheses, brackets, and braces?
DSA Java
import java.util.Stack;

public class BalancedSymbols {
    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 (c == ')' || c == ']' || c == '}') {
                if (stack.isEmpty()) {
                    return false;
                }
                char top = stack.pop();
                if ((c == ')' && top != '(') ||
                    (c == ']' && top != '[') ||
                    (c == '}' && top != '{')) {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("{[()()]()}"));
    }
}
ACompilation error
Btrue
Cfalse
DRuntime exception
Attempts:
2 left
💡 Hint
Check matching pairs for all types of brackets.

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