Implement "N" stacks in an Array
Pattern: Implementation
Keep k stacks in one array of n slots. Each slot has a next index: for a used slot it points to the slot below it in its stack, for a free slot to the next free slot. A push takes the first free slot; a pop gives it back. Every slot can serve any stack.
The problem
Build KStacks(k, n) holding k stacks in one array of n slots: push(x, sn) pushes x onto stack sn and
returns true, or false when all n slots are used; pop(sn) returns the top of stack sn or -1 if it is empty.
Stacks are numbered from 0.
The linked page solves the same task; this guide's return values are its own.
Think first
- Why does splitting the array into k equal parts fail?
- What does each stack need to know to pop?
- How can you find a free slot in O(1)?
Hints
Brute force, and why it fails
Divide the array into k blocks of n / k: O(1) operations but a push can fail while other blocks are empty.
The key insight
One next array serves two lists at once: inside a stack it points down, among free slots it points to the next free one. Push moves a slot from the free list to a stack; pop moves it back.
Dry run
| free | 0 |
|---|---|
| next | 1 2 3 4 -1 |
KStacks(3, 5): every slot is free, chained 0 -> 1 -> 2 -> 3 -> 4. All tops are -1.
The plan
push(x, sn): if free == -1: return false
i = free; free = next[i]
arr[i] = x; next[i] = top[sn]; top[sn] = i; return true
pop(sn): if top[sn] == -1: return -1
i = top[sn]; top[sn] = next[i]
next[i] = free; free = i; return arr[i]
Complexity
- Time
O(1) per operation- Space
O(n + k)
Each operation relinks two slots. The arrays arr, next and top take n + n + k integers.
Edge cases
- All slots used by one stack.
- A pop from a stack that never had a push.
- n = 1.
I've built my logic, show the code
Java
import java.util.*;
class KStacks {
private final int[] arr, next, top; // next[i]: the slot below i in its stack, or the next free slot
private int free = 0; // the first free slot
public KStacks(int k, int n) {
arr = new int[n];
next = new int[n];
top = new int[k];
Arrays.fill(top, -1);
for (int i = 0; i < n - 1; i++) next[i] = i + 1; // at first every slot is free, chained in order
next[n - 1] = -1;
}
public boolean push(int x, int sn) {
if (free == -1) return false; // no free slot anywhere
int i = free;
free = next[i]; // take the slot off the free list
arr[i] = x;
next[i] = top[sn]; // it sits on top of stack sn
top[sn] = i;
return true;
}
public int pop(int sn) {
if (top[sn] == -1) return -1;
int i = top[sn];
top[sn] = next[i]; // the slot below becomes the top
next[i] = free; // give the slot back to the free list
free = i;
return arr[i];
}
}C++
class KStacks {
public:
vector<int> arr, nxt, top; // nxt[i]: the slot below i in its stack, or the next free slot
int freeSlot = 0; // the first free slot
KStacks(int k, int n) : arr(n), nxt(n), top(k, -1) {
for (int i = 0; i < n - 1; i++) nxt[i] = i + 1; // at first every slot is free, chained in order
nxt[n - 1] = -1;
}
bool push(int x, int sn) {
if (freeSlot == -1) return false; // no free slot anywhere
int i = freeSlot;
freeSlot = nxt[i]; // take the slot off the free list
arr[i] = x;
nxt[i] = top[sn]; // it sits on top of stack sn
top[sn] = i;
return true;
}
int pop(int sn) {
if (top[sn] == -1) return -1;
int i = top[sn];
top[sn] = nxt[i]; // the slot below becomes the top
nxt[i] = freeSlot; // give the slot back to the free list
freeSlot = i;
return arr[i];
}
};Python
class KStacks:
def __init__(self, k: int, n: int):
self.arr = [0] * n
self.next = list(range(1, n)) + [-1] # the slot below in its stack, or the next free slot
self.top = [-1] * k
self.free = 0 # the first free slot
def push(self, x: int, sn: int) -> bool:
if self.free == -1:
return False # no free slot anywhere
i = self.free
self.free = self.next[i] # take the slot off the free list
self.arr[i] = x
self.next[i] = self.top[sn] # it sits on top of stack sn
self.top[sn] = i
return True
def pop(self, sn: int) -> int:
if self.top[sn] == -1:
return -1
i = self.top[sn]
self.top[sn] = self.next[i] # the slot below becomes the top
self.next[i] = self.free # give the slot back to the free list
self.free = i
return self.arr[i]Common mistakes
- Forgetting to link a popped slot back into the free list.
- Overwriting
next[i]before reading the next free slot.