Sub topic 8
Stack applications: balanced parentheses, infix to postfix, postfix evaluation
This chapter assumes you know the stack operations push, pop and peek, that each costs O(1), and that you can read short Python. It covers three standard uses of a stack that GATE CS asks about often. You will implement each one and trace it by hand, because the exam asks for traces more than for code.
Why a stack fits these problems
All three problems have the same shape. You scan input from left to right and keep items that are still waiting for a partner. The item you resolve first is the one you saw most recently. That is last-in, first-out (LIFO) order, so a stack is the natural structure.
Balanced parentheses
A string is balanced if every closing bracket matches the most recent unmatched opening bracket of the same type. Push each opener. On a closer, pop and compare.
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
return not stackThere are three ways to fail:
- A closer arrives when the stack is empty (underflow), as in
)(. - A closer meets the wrong opener on top, as in
(]. - The input ends with openers left on the stack, as in
((.
The code returns not stack at the end to catch the third case. If you forget it, "((" is wrongly accepted.
The time is O(n) and the extra space is O(n) in the worst case. If the string has only one bracket type, a counter replaces the stack and the space drops to O(1). With several bracket types the counter is not enough, because it cannot tell ([)] from ([]).
Infix and postfix notation
Infix puts the operator between operands: a + b. Postfix (reverse Polish notation) puts it after them: a b +. Postfix needs no parentheses and no precedence rules, because the order of the tokens fixes the order of evaluation.
The conversion uses an operator stack. Operands go straight to the output. For each operator, first pop any operators on the stack that must run before it. Then push it.
| Operator | Precedence | Associativity |
|---|---|---|
| `^` | 3 (highest) | right |
| `*`, `/` | 2 | left |
| `+`, `-` | 1 | left |
The conversion rules
- Operand: append it to the output.
(: push it.): pop operators to the output until(is on top, then discard the(.- Operator: while the top of the stack is not
(and has higher precedence than the new operator, or equal precedence with the new operator left-associative, pop it to the output. Then push the new operator. - At the end of input, pop everything remaining to the output.
PREC = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
RIGHT = {'^'}
def to_postfix(tokens):
out, st = [], []
for t in tokens:
if t == '(':
st.append(t)
elif t == ')':
while st[-1] != '(':
out.append(st.pop())
st.pop()
elif t in PREC:
while (st and st[-1] != '(' and
(PREC[st[-1]] > PREC[t] or
(PREC[st[-1]] == PREC[t] and t not in RIGHT))):
out.append(st.pop())
st.append(t)
else:
out.append(t)
while st:
out.append(st.pop())
return out
print(' '.join(to_postfix(list('a+b*c-d'))))The program prints a b c * + d -.
Tracing `a+b*c-d`
| Token | Stack (bottom to top) | Output |
|---|---|---|
| a | empty | a |
| + | + | a |
| b | + | a b |
| * | + * | a b |
| c | + * | a b c |
| - | - | a b c * + |
| d | - | a b c * + d |
| end | empty | a b c * + d - |
At -, the * is popped because it has higher precedence. The + is also popped because it has equal precedence and is left-associative. This is the step most often missed.
Associativity matters
For a^b^c, the right-associative ^ is not popped by an incoming ^, so the result is a b c ^ ^. For a-b-c, the left-associative - is popped, so the result is a b - c -. Questions that mix ^ with other operators test exactly this rule.
Evaluating postfix
Scan left to right. Push each operand. On an operator, pop two values, apply the operator, and push the result. When the input ends, one value remains on the stack: the answer.
OPS = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: a / b,
'^': lambda a, b: a ** b,
}
def eval_postfix(tokens):
st = []
for t in tokens:
if t in OPS:
b = st.pop()
a = st.pop()
st.append(OPS[t](a, b))
else:
st.append(float(t))
return st.pop()
print(eval_postfix('5 6 2 + * 12 4 / -'.split()))The program prints 37.0. The value popped first is the right operand. For -, / and ^, swapping the two gives a wrong answer, and this is a common exam trap.
Costs
Both conversion and evaluation are O(n) in time. Each token is pushed at most once and popped at most once. The stack depth is bounded by the number of operators and open parentheses (conversion) or by the number of operands waiting for an operator (evaluation). A GATE question may ask for the maximum stack depth during a conversion. To answer it, trace the algorithm and record the largest stack size. A heuristic will not do.
The call stack and recursion
Recursion is the same idea built into the language. Each call pushes a frame that holds its parameters, local variables and return address. A return pops it. Unbounded recursion overflows the stack. Any recursive function can be rewritten with an explicit stack, which is the usual way to avoid that overflow. Depth-first traversal is a common example.
Common errors
- Applying left associativity to
^. - Discarding the
(before the operators above it are popped, or leaving it in the output. - Forgetting the final
not stackcheck when testing balance. - Treating unary minus as binary. The code above does not handle it.
- Assuming operators of equal precedence never pop each other.
Exercise
Convert the infix expression a*(b+c)/d to postfix. What is the maximum number of symbols on the operator stack at any moment?
Show answer
The postfix form is a b c + d /. The stack reaches ( + at its peak, so the maximum depth is 3. When ) arrives, + is popped and ( is discarded. When / arrives, * has equal precedence and is left-associative, so it is popped before / is pushed.
Exercise
Evaluate the postfix expression 8 2 3 ^ / 2 3 * + 5 - .
Show answer
2 3 ^ gives 8, then 8 8 / gives 1. 2 3 * gives 6, then 1 6 + gives 7. Finally 7 5 - gives 2. The answer is 2.