Two stacks in one array
Two stacks grow toward each other from the two ends of one array; neither is full until the whole array is.
Giving each stack its own fixed-size array lets one fill up while the other sits empty. Putting two stacks in one array, growing toward each other from the two ends, means neither is full until the whole array is.
Read the full explanation ↓- Time:
O(1) per operation - Space:
O(n) shared - Horowitz–Sahni, chapter 3
Each row is [stack, value], and a value of 0 means POP. The stacks grow from the two ends, then each pops one item.
def two_stacks(ops):# ops: rows [stack (1 or 2), value]; a value of 0 pops. Stack 1 grows from the left, stack 2 from the right.n = 8arr = ["·"] * ncells = [arr] # for the picture: the shared array as one table rowtop1, top2 = -1, npopped = []for which, value in ops:if value != 0:if top1 + 1 == top2:continueif which == 1:top1 = top1 + 1arr[top1] = valueelse:top2 = top2 - 1arr[top2] = valueelif which == 1:if top1 == -1:continuepopped.append(arr[top1])arr[top1] = "·"top1 = top1 - 1else:if top2 == n:continuepopped.append(arr[top2])arr[top2] = "·"top2 = top2 + 1return popped
Start
The table is still empty.
Local variables
Orange = changed in this step
ops list
Call stack
- two_stacks()line 1
Explanation
The idea
Giving each stack its own fixed-size array lets one fill up while the other sits empty. Putting two stacks in one array, growing toward each other from the two ends, means neither is full until the whole array is.
- Stack 1:
top1starts at−1and grows by one with each PUSH. - Stack 2:
top2starts atnand shrinks by one with each PUSH. - The array is full when
top1 + 1 = top2.
More than two stacks
For m stacks (as in Horowitz–Sahni) the array is first split into m equal parts; when a stack reaches the next
part's boundary, the neighbouring stacks are shifted to bring it free space. With two stacks no shifting is ever
needed.
The input
Each row is [stack, value], and a value of 0 means POP. The array has 8 cells.