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.rb
def match_open(close)
if close == ')'
return '('
elsif close == ']'
return '['
elsif close == '}'
return '{'
end
' '
end
text = "({[]})"
stack = []
balanced = true
i = 0
while balanced && i < text.length
ch = text[i]
if ch == '(' || ch == '[' || ch == '{'
stack << ch
else
if stack.empty? || stack[-1] != match_open(ch)
balanced = false
else
stack.pop
end
end
i = i + 1
end
if !stack.empty?
balanced = false
end
if balanced
puts "True"
else
puts "False"
end
Complexity
- Time: O(n)
- Space: O(n) worst case
Implementation notes
- Ruby: a plain
Arraywith<</pop/stack[-1]/stack.empty?is the smallest honest stack shape; reaching for a wrapper class would hide the explicit push/pop pattern. Abalancedflag pluswhile balanced && i < text.lengthloop keeps the early-exit visible without leaning onbreak. - The
match_openhelper 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 a plain `Array` as the open-bracket stack; push by `stack << ch`, pop by `stack.pop`.
matching map
A small `match_open(close)` helper returns the expected opener for each closing bracket — three explicit `if`/`elsif` arms keep the lesson compact.