Matching brackets
After this: Follow the bracket scan with a stack and write its last line.
On this page · 6 sections · 4 checks
You now know what a stack is. Here is a real job for one.
Code is full of brackets: (, [ and {. Each opening bracket needs a closing bracket of the same kind, and the pairs must sit inside each other properly. A string that follows these rules is called balanced. Your editor and your compiler check this all the time. How do they do it?
Look at two strings. {[()]} is balanced. ([)] is not, and yet it has two opening brackets and two closing brackets, and each one has a partner. The problem is the order. The [ was opened after the (, so the [ has to close first.
Counting brackets cannot see this, because counting forgets the order. A stack remembers the order.
The smallest example
We will call an opening bracket an opener and a closing bracket a closer. Read the string [()] from left to right, and keep the openers on a stack.
- Read
[. It is an opener, so push it. The stack holds[. - Read
(. It is an opener, so push it. The stack holds[with(on top. - Read
). It is a closer, so pop. The pop gives(, which is the right partner. The stack holds[. - Read
]. It is a closer, so pop. The pop gives[, which is the right partner. The stack is empty.
The string has ended and the stack is empty, so the string is balanced.
The rules
That example used all three rules.
- An opener is pushed. It waits on the stack until it is closed.
- A closer pops. The popped opener must be its partner. If it is not, or if the stack is empty, the string is not balanced.
- At the end, the stack must be empty. Any opener still there was never closed.
A stack fits this job because the most recent opener must close first. That is last in, first out.
The code
def is_balanced(s): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in s: if ch in "([{": stack.append(ch) # an opener waits on the stack elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False # nothing to close, or the wrong thing return not stack # balanced only if nothing is left waiting
print(is_balanced("{[()]}"), is_balanced("([)]"), is_balanced("(("))True False False
import java.util.*;
public class Brackets { static boolean isBalanced(String s) { Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{'); Deque<Character> stack = new ArrayDeque<>(); for (char ch : s.toCharArray()) { if ("([{".indexOf(ch) >= 0) { stack.push(ch); // an opener waits on the stack } else if (pairs.containsKey(ch)) { if (stack.isEmpty()) return false; // nothing to close char opener = stack.pop(); if (opener != pairs.get(ch)) return false; // the wrong thing is waiting } } return stack.isEmpty(); // balanced only if nothing is left waiting }
public static void main(String[] args) { System.out.println(isBalanced("{[()]}") + " " + isBalanced("([)]") + " " + isBalanced("((")); }}true false false
Here is how to read it.
pairssays which opener each closer needs. For example,)needs(.- The loop reads one character at a time. An opener is pushed. A closer pops and compares. Any other character, such as a letter, is skipped.
- Inside the loop, the function stops as soon as it finds a problem, and it returns Falsefalse.
- The last line of the function returns whether the stack is empty.
The last line of the program tests three strings, and here is how each one goes.
{[()]}: push{, push[, push(. Then)pops(,]pops[, and}pops{. The stack is empty at the end, so it is balanced.([)]: push(, push[. Then)pops[, which is the wrong partner. It is not balanced, and the scan stops there.((: two pushes and no pops. The stack is not empty at the end, so it is not balanced.
So a string can fail in two ways. Either a closer finds the wrong opener on top, or nothing on top, as in ). Or openers are left over when the string ends.
Watch it happen
Scan ([]){} on the stack. The visualizer stores numbers, so 1 stands for (, 2 for [ and 3 for {.
- Push 1Read (: an opener. Push it. (1 stands for a round bracket.)
- Push 2
- Pop
- Pop
- Push 3
- Pop
- 3·
- 2·
- 1·
- 0·
Run an operation to begin.
Check yourself
You are scanning {[()]}. After the first four characters, which are {[(), what is on the stack, from bottom to top?
You are scanning ([)]. What happens when ) is read, and what does it tell you?
What does this print?
def is_balanced(s): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in s: if ch in "([{": stack.append(ch) # an opener waits on the stack elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False # nothing to close, or the wrong thing return not stack # balanced only if nothing is left waiting
print(is_balanced("{[()]}"), is_balanced("([)]"), is_balanced("(("))import java.util.*;
public class Brackets { static boolean isBalanced(String s) { Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{'); Deque<Character> stack = new ArrayDeque<>(); for (char ch : s.toCharArray()) { if ("([{".indexOf(ch) >= 0) { stack.push(ch); // an opener waits on the stack } else if (pairs.containsKey(ch)) { if (stack.isEmpty()) return false; // nothing to close char opener = stack.pop(); if (opener != pairs.get(ch)) return false; // the wrong thing is waiting } } return stack.isEmpty(); // balanced only if nothing is left waiting }
public static void main(String[] args) { System.out.println(isBalanced("{[()]}") + " " + isBalanced("([)]") + " " + isBalanced("((")); }}The loop has read the whole string and found no mismatch. Write the last line: the string is balanced only if nothing is left waiting on the stack.
def is_balanced(s): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in s: if ch in "([{": stack.append(ch) elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False ______________________ # ← the verdict after the whole string has been read static boolean isBalanced(String s) { Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{'); Deque<Character> stack = new ArrayDeque<>(); for (char ch : s.toCharArray()) { if ("([{".indexOf(ch) >= 0) { stack.push(ch); } else if (pairs.containsKey(ch)) { if (stack.isEmpty()) return false; char opener = stack.pop(); if (opener != pairs.get(ch)) return false; } } ______________________ // ← the verdict after the whole string has been read }Connect
- Scan a string with a stack: push every opener, and on every closer pop and compare.
- Say what is on the stack at any point of the scan.
- Name the two ways a string fails: a closer finds the wrong opener or nothing on top, or openers are left over at the end.