4.3Stack Applications
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 stack, and it is solved in a single pass.
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 LIFO rule of a stack.
The algorithm reads the string once, left to right. When it sees an opener ((, [, {), it puts it on the stack with push. When it sees a closer, it takes the top opener off with pop 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:
| Input | What happens | Kind 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 underflow. 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.
- Start. The input is
{[]()}and the stack is empty. The string will be read once, left to right. {is an opener. It is pushed; the stack now holds{.[is an opener too. It is pushed and sits on top of{. The top is[.]is a closer. The stack is not empty; the pop returns[.[and]form a pair. The top is{again.(is an opener and is pushed. The stack:{,(.)arrives. The pop returns(; the pair is right. Only{is left on the stack.}arrives. The pop returns{; the pair is right. The stack is empty.- 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 leftThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
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 ([)]?
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.
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?
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.
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.