Stack with MULTIPOP (amortized analysis)
One MULTIPOP may remove many items and be expensive, but each item is popped at most once; so n operations cost at most 2n in total.
A stack with three operations: PUSH(x), POP and MULTIPOP(k), which removes up to k items from the top. One
MULTIPOP can cost O(n), so you might think n operations cost O(n²).
- Time:
O(1) amortized per operation - Space:
O(n) - CLRS, section 16.1
Positive numbers are PUSH and negative ones MULTIPOP: six PUSHes, MULTIPOP(4), two PUSHes and MULTIPOP(10). The total cost is 16 for 10 operations (8 pushes and 8 pops), under 2 × 10.
def multipop_stack(ops):# A positive number pushes itself; −k pops up to k items at once (0 pops nothing).stack = []cost = 0for op in ops:if op > 0:stack.append(op)cost = cost + 1else:k = -opwhile stack and k > 0:stack.pop()k = k - 1cost = cost + 1return cost
Start
Local variables
Orange = changed in this step
ops list
Call stack
- multipop_stack()line 1
Explanation
The idea
A stack with three operations: PUSH(x), POP and MULTIPOP(k), which removes up to k items from the top. One
MULTIPOP can cost O(n), so you might think n operations cost O(n²).
Amortized analysis
Each item is pushed once and popped at most once. So the total number of pops (even inside MULTIPOPs) is at most the
number of pushes, and n operations cost at most 2n: O(1) amortized per operation.
The potential method: let the potential be the number of items on the stack. PUSH raises it by one (amortized cost 2), and each pop spends one unit of potential (amortized cost 0).
The input
A positive number means PUSH that number, and a negative number −k means MULTIPOP(k).
What to watch in the trace
- The bars are the stack (the top is on the right).
costin the memory panel is the total so far.