![]() |
VOOZH | about |
Given two integers n and k. Implement k stacks using a single array of size n. Multiple stacks must share the same array space while supporting the following operations:
push(x, i): Push element x into the i-th stack.
pop(i): Pop the top element from the i-th stack and return it.
Table of Content
The idea is to divide the array into fixed parts, one for each stack. If the array size is n and there are k stacks, then each stack gets n/k slots.
We maintain another array top[] of size k, where top[i] stores the index of the top element of the i-th stack. Initially, all top[i] are set to the start of their respective segments minus one (indicating empty stacks).
Push is done by incrementing top[i] and inserting the element, while pop is done by returning the element at top[i] and then decrementing it.
Limitation: This approach leads to inefficient space utilization, since one stack may become full even when other stacks still have free space available.
Stack 0 overflow Poped Element: 9 Poped Element: 15 Stack 1 underflow
Time Complexity: O(1) for push operation and pop operation
Auxiliary Space: O(n)
The idea is to allow all stacks to share the array dynamically instead of dividing it into fixed parts. For this, we use three additional structures:
Push Operation:
When we push an element into stack i, we pick the first free slot from freeTop. The element is placed at this index, and the next[] array is updated to link this slot with the previous top of stack i. Finally, top[i] is updated to this new index, and freeTop moves to the next available free slot.
Pop Operation:
When we pop from stack i, we look at the index stored in top[i]. The element at that index is removed, and top[i] is updated to the next link stored in next[]. The freed index is then added back to the free list by updating freeTop.
Illustrations:
Popped Element: 30 Popped Element: 20 Popped Element: 200
Time Complexity: O(1) for push operation and pop operation
Auxiliary Space: O(n)
Related Article: