Stacks and Queues
Balanced Parentheses
Walk a string of bracket characters. Push every opening bracket. On a closing bracket, pop and verify it matches; mismatch or empty-stack pop means unbalanced. At end of string, stack must be empty.
Algorithm
Canonical input "({[]})" (balanced) finishes with the stack empty and
the result true.
Basic Implementation
basic.swift
func matchOpen(_ close: Character) -> Character {
switch close {
case ")": return "("
case "]": return "["
case "}": return "{"
default: return " "
}
}
let text = "({[]})"
var stack: [Character] = []
var balanced = true
for ch in text {
if ch == "(" || ch == "[" || ch == "{" {
stack.append(ch)
} else {
if stack.isEmpty || stack.last! != matchOpen(ch) {
balanced = false
break
}
stack.removeLast()
}
}
if !stack.isEmpty {
balanced = false
}
print(balanced ? "True" : "False")
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- Swift:
var stack: [Character]withappend/removeLast/lastis the smallest honest stack shape; the stdlibArrayalready exposes a proper LIFO API so the lesson can stay on the explicit push/pop pattern instead of importingFoundation. - The
matchOpenhelper documents the closing -> opening map without leaking runtime references into the replay. - The replay highlights the current character, shows the stack updating each frame, and surfaces the final balanced/unbalanced verdict.
stack push/pop
Use an `[Character]` array as the open-bracket stack; push by `stack.append(ch)`, pop by `stack.removeLast()`.
matching map
A small `matchOpen(close)` helper returns the expected opener for each closing bracket — three explicit `switch` arms keep the lesson compact.