algoritmauzmanı
Sign in
TREN
4.3Stack Applications
Lesson 4.3.1

Balanced parentheses

A compiler reading a source file, you writing a math expression, an editor highlighting the matching bracket: they all ask the same question. Did every bracket that was opened close in the right place? This is the best-known use of a , and it is solved in a single pass.

What you will learn
  • Why balanced brackets follow the order
  • How to check an expression in one pass: the openers, and compare on each closer
  • The three kinds of imbalance: a wrong pair, a closer with an empty stack, and an opener left open
7 minTime O(n)Memory O(n)C · Java · Python

1Idea

In an expression every opening bracket must be closed by a bracket of the same kind, in the right order. {[]()} is balanced. ([)] is not: the counts match, but ) arrives before [ is closed. The rule is: the bracket opened last closes first. That is exactly the rule of a .

The algorithm reads the string once, left to right. When it sees an opener ((, [, {), it puts it on the stack with . When it sees a closer, it takes the top opener off with and checks whether the two form a pair. Any other character (a letter, a digit, an operator) is skipped.

The expression is unbalanced in three cases, and the algorithm catches all of them:

InputWhat happensKind of failure
(]On ] the pop returns (; the two do not pair.Wrong pair
)(The first character is a closer, but the stack is empty; there is nothing to pop.Closer without an opener
((The string ends with two ( still on the stack.Opener left open

The empty check comes before the pop; without it you get an . The final check is not skipped either: if the stack is not empty when the string ends, some bracket was never closed. An empty string is balanced, because no bracket was opened.

The stack used here can be the one you built with an array or with a linked list. The algorithm only needs push, pop and an empty check, and both do the same job. To keep the code short, C uses an array and a top index inside the function, Java uses java.util.ArrayDeque, and Python uses a list.

In C the array has length strlen(s) + 1. In the worst case every character is an opener, so the stack never overflows.

2Step by step

The drawing checks the string {[]()}. i marks the character being read. The stack under the drawing holds the openers; the bottom line is the top. Brackets that have been matched turn green.

{0[1]2(3)4}5i
Stack (the bottom line is the top)
  1. Start. The input is {[]()} and the stack is empty. The string will be read once, left to right.
  2. { is an opener. It is pushed; the stack now holds {.
  3. [ is an opener too. It is pushed and sits on top of {. The top is [.
  4. ] is a closer. The stack is not empty; the pop returns [. [ and ] form a pair. The top is { again.
  5. ( is an opener and is pushed. The stack: {, (.
  6. ) arrives. The pop returns (; the pair is right. Only { is left on the stack.
  7. } arrives. The pop returns {; the pair is right. The stack is empty.
  8. The string has ended and the stack is empty: every bracket closed in the right order. The result is true.

bool isBalanced(const char* s) {    char stack[strlen(s) + 1];  // stack: open brackets    int top = -1;    for (int i = 0; s[i] != '\0'; i++) {        char c = s[i];        if (c == '(' || c == '[' || c == '{') {            stack[++top] = c;              // push        } else if (c == ')' || c == ']' || c == '}') {            if (top == -1) return false;   // a closer, but the stack is empty            char open = stack[top--];      // pop            if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{'))                return false;              // wrong pair        }    }    return top == -1;  // balanced if no opener is left}
boolean isBalanced(String s) {    java.util.ArrayDeque<Character> stack = new java.util.ArrayDeque<>();    for (int i = 0; i < s.length(); i++) {        char c = s.charAt(i);        if (c == '(' || c == '[' || c == '{') {            stack.push(c);        } else if (c == ')' || c == ']' || c == '}') {            if (stack.isEmpty()) return false;  // a closer, but the stack is empty            char open = stack.pop();            if ((c == ')' && open != '(') || (c == ']' && open != '[') || (c == '}' && open != '{'))                return false;                   // wrong pair        }    }    return stack.isEmpty();  // balanced if no opener is left}
def is_balanced(s):    pair = {")": "(", "]": "[", "}": "{"}    stack = []                   # stack: open brackets    for c in s:        if c in "([{":            stack.append(c)      # push        elif c in pair:            if not stack:                return False     # a closer, but the stack is empty            if stack.pop() != pair[c]:                return False     # wrong pair    return not stack             # balanced if no opener is left

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

Each character is read once; push and pop take .

Memory
O(n)

In the worst case (like (((() every character goes on the stack.

With only one kind of bracket a counter would do instead of a stack: +1 for an opener, -1 for a closer. With several kinds you also need to know which bracket is open; a counter cannot hold that, a stack can.

4Common mistake

The most common mistake is to forget the final empty check and return true right after the loop:

    }    return true;  // also returns true for "(("

The loop only catches a wrong pair and a closer that meets an empty stack. The input (( has no closer at all, so the loop ends without trouble. You only see the unclosed brackets by checking, after the string ends, whether the stack is empty.

5Try it

Where does the algorithm return false for the input ([)]?

Show the answer

The answer is A. ( and [ are pushed; the top is [. When ) arrives, the pop returns [. [ and ) do not pair, so the algorithm returns false at once.

What does it mean if elements are left on the stack when the string ends?

Show the answer

The answer is B. Only openers sit on the stack. Each closer removes one opener. Every element left at the end is an opener whose partner never came.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.