Multiple stacks in one array
Fit two (or n) stacks into one array without wasting space.
Syllabus says: “Multi-Stacks”
On this page · 8 sections
Two stacks = two people eating one dosa from opposite ends — it's ‘full’ only when they MEET in the middle.
One long shelf, two families: one stacks bags from the left wall, the other from the right wall. Space is shared, so neither runs out early.
Two stacks share one array by growing from opposite ends (top1 from −1 upward, top2 from MAX downward); overflow occurs only when top1 + 1 = top2.
What you will be able to do
- Implement two stacks in one array.
- Explain how n stacks share one array using boundary[] and top[].
n stacks in one array
Divide memory[0..MAX−1] into n segments. boundary[i] is the position just before segment i begins; top[i] is the top of stack i. Initially top[i] = boundary[i] = (MAX/n)·i − 1, and boundary[n] = MAX − 1.
- Stack i is empty when top[i] = boundary[i].
- Stack i is full when top[i] = boundary[i + 1].
- Push(i, x): if full → stackFull(i); else memory[++top[i]] ← x.
- Pop(i): if empty → error; else return memory[top[i]−−].
When stack i is full but there is free space elsewhere, find a stack j with free space (first to the right, else to the left) and shift the stacks in between by one position to make room. The shifting costs time, which is the price of sharing.
Two stacks, one array
top1 ← −1; top2 ← MAX
Push1(x): if top1 + 1 = top2 then overflow else top1 ← top1 + 1; a[top1] ← x
Push2(x): if top1 + 1 = top2 then overflow else top2 ← top2 − 1; a[top2] ← x
Pop1(): if top1 = −1 then underflow else x ← a[top1]; top1 ← top1 − 1; return x
Pop2(): if top2 = MAX then underflow else x ← a[top2]; top2 ← top2 + 1; return xComplexity
Two stacks: every operation O(1). n stacks: push and pop are O(1) unless a shift is needed, which can cost O(MAX) in the worst case.
Quick check — can you get them all?
Practice
Every visualizer has a Practice mode: predict the next state before the animation reveals it. You can also work through the topic's question set on the practice page.
Exam-ready summary
- Two stacks grow towards each other: top1 = −1, top2 = MAX.
- Full when top1 + 1 = top2.
- n stacks: boundary[] and top[]; full when top[i] = boundary[i+1]; shift to make room.
References
- Horowitz, Sahni & Anderson-Freed, Fundamentals of Data Structures in C, 2/e — §3.4 (Multiple stacks and queues)
Explanations on this page are original. Textbook references point to where the standard treatment can be read; no text is reproduced from them.
Prefer revising from notes? Module-wise notes and question papers on Azhimathi Mayam (opens in a new tab)