Placement Prep

Balanced Parenthesis Checker: Stack-Based Solution With Code

Step-by-step guide to checking balanced parentheses using a stack in Python and Java, with time and space complexity analysis for placement rounds.

By FACE Prep Team 5 min read
balanced-parenthesis stack data-structures placement-prep python java algorithms

A balanced parenthesis checker validates that every opening bracket in an expression has a matching closing bracket of the same type, in the correct order.

That is the full problem statement. Input: a string. Output: 1 if balanced, -1 if not. Simple to state, easy to get wrong on edge cases.

What “balanced” means (and what it doesn’t)

Three bracket types matter: parentheses (), square brackets [], and curly braces {}. An expression is balanced when every opening bracket has a corresponding closing bracket, pairs close in the reverse order they opened (last opened, first closed), and no closing bracket appears when the stack is empty.

Some test cases to fix the definition:

ExpressionResultReason
((()))1Opens 3, closes 3, correct order
{[()]}1Three types, correctly nested
()((-1Two unclosed ( remain
{(})-1Mis-nested: ) closes before }
][-1Closing bracket with empty stack
(empty)1Nothing to mismatch

The mis-nesting case {(}) deserves attention. It has equal counts of opening and closing brackets, yet it is unbalanced. A counter-based check would wrongly return 1 here. The stack-based check handles it correctly, which is why interviewers reach for this example.

Stack-based approach

A stack’s LIFO property (last in, first out) maps directly to bracket nesting. The algorithm:

  • When you encounter an opening bracket ((, [, {), push it onto the stack.
  • When you encounter a closing bracket (), ], }), check the stack:
    • Stack is empty: return -1 (no matching open bracket exists).
    • Top of stack matches: pop the top.
    • Top of stack does not match: return -1 (wrong bracket type).
  • After scanning the full expression: return 1 if the stack is empty, -1 if not.

Python implementation

def is_balanced(expression):
    stack = []
    matching = {')': '(', ']': '[', '}': '{'}
    open_brackets = set(matching.values())

    for char in expression:
        if char in open_brackets:
            stack.append(char)
        elif char in matching:
            if not stack or stack[-1] != matching[char]:
                return -1
            stack.pop()

    return 1 if not stack else -1

Verify against the table:

print(is_balanced("((()))"))  # 1
print(is_balanced("{[()]}"))  # 1
print(is_balanced("()(("))    # -1
print(is_balanced("{(})"))    # -1
print(is_balanced(""))        # 1

Python’s built-in list works as a stack here. append() is push, pop() is pop, both O(1) amortised. The Python documentation on using lists as stacks covers this in detail.

Java implementation

import java.util.Stack;

public class BalancedParenthesis {
    public static int isBalanced(String expression) {
        Stack<Character> stack = new Stack<>();

        for (char ch : expression.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else if (ch == ')' || ch == ']' || ch == '}') {
                if (stack.isEmpty()) return -1;
                char top = stack.pop();
                if ((ch == ')' && top != '(') ||
                    (ch == ']' && top != '[') ||
                    (ch == '}' && top != '{')) {
                    return -1;
                }
            }
        }

        return stack.isEmpty() ? 1 : -1;
    }
}

The logic is identical to the Python version. Java’s Stack<Character> is from java.util; push(), pop(), and isEmpty() are the three methods you need.

Counter-based approach (single bracket type only)

For expressions with only parentheses (), a counter replaces the stack:

  • Start with count = 0.
  • Increment on (, decrement on ).
  • If count drops below 0 at any point, return -1 immediately.
  • After the full scan: return 1 if count == 0, else -1.

Python implementation

def is_balanced_counter(expression):
    count = 0
    for char in expression:
        if char == '(':
            count += 1
        elif char == ')':
            count -= 1
            if count < 0:
                return -1
    return 1 if count == 0 else -1

This uses O(1) space: no auxiliary data structure is needed. The tradeoff is that it cannot distinguish bracket types. Feed it {(}) and it returns 1 (equal counts) instead of -1 (mis-nested). That is wrong.

Use the counter method only when:

  • The problem explicitly guarantees a single bracket type.
  • The question asks about space optimisation and confirms single-type input.

Prefer the stack method in every other case. The GeeksforGeeks reference on balanced parentheses also covers the edge cases where counter methods produce wrong answers.

Time and space complexity

ApproachTime complexitySpace complexity
Stack-basedO(n)O(n)
Counter-basedO(n)O(1)

Both approaches scan each character exactly once, so time complexity is O(n) for both. The difference is space: the stack can hold up to n characters in the worst case (all opening brackets, no closing bracket before end), while the counter is a single integer. For a deeper look at how auxiliary space affects algorithm selection, see FACE Prep’s guide on space complexity of algorithms.

One practical note: the O(n) space for the stack is linear in the length of the expression, not a fixed overhead. The stack grows with input size: a worst-case expression of all opening brackets fills the stack to capacity. The counter stays at one integer regardless of input size. If the problem gives a tight memory constraint, that is when the counter trade-off becomes relevant, and the problem statement will tell you it is single-bracket type.

Where this appears in placement tests

The balanced parenthesis problem is a standard moderate-difficulty question in coding rounds. It tests three things simultaneously: stack manipulation, edge-case awareness, and clean implementation under time pressure.

Common formats:

  • Direct “write the function” with multiple test cases including empty strings and mis-nested inputs.
  • A sub-problem inside an expression evaluator or a simple syntax validator.
  • A variant asking for the index of the first unmatched bracket rather than 1/-1.

Practise this alongside similar single-pass traversal problems. The equilibrium index problem builds the same left-to-right scan instinct. Problems like finding symmetric pairs in an array build the hash-map and stack pattern recognition that appears across multiple coding-round question types.

Write both the stack and counter versions from scratch until you can produce them in under five minutes without looking anything up. That is the standard for a coding section under time pressure, where you do not get to Google edge cases mid-exam.

The same stack logic that validates {[()]} in a placement coding round is what parses JSON bracket structure in LLM API responses. If you want to see that in practice as a working project, TinkerLLM puts live API calls in your hands for ₹299, and the resulting parser or structured-output validator is something you can actually show in an interview when a recruiter asks what you have shipped.

Primary sources

Frequently asked questions

What is the time complexity of a balanced parenthesis checker using a stack?

O(n) where n is the length of the expression. Each character is visited once and each push and pop on the stack is O(1).

Can I check balanced parentheses without a stack?

Yes, for single-bracket expressions. A counter increments on ( and decrements on ), returning 1 if the final count is 0. It fails for mixed brackets like {[()]}.

Why does the counter method fail for multiple bracket types?

A counter tracks quantity but not order or type. The expression {(}) has equal opening and closing counts yet is unbalanced because the types mis-nest.

What should the program return for an empty string?

An empty string is considered balanced. The stack stays empty and the counter stays at 0, so both approaches return 1.

Does mis-nesting like {(}) count as balanced?

No. The closing ) matches the ( correctly, but then } finds an empty stack instead of {. The stack-based checker correctly returns -1.

Where does the balanced parenthesis problem appear in placement tests?

It appears in the coding sections of TCS NQT, Wipro NLTH, and Infosys Specialist Programmer tests, typically as a moderate-difficulty stack problem.

Build AI projects

A self-paced playground for building with LLMs.

TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.

Try TinkerLLM (₹299 launch)
Free AI Roadmap PDF