VOOZH about

URL: https://www.geeksforgeeks.org/dsa/efficiently-implement-k-stacks-single-array/

⇱ Implement k stacks in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement k stacks in an array

Last Updated : 22 Sep, 2025

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.

[Naive Approach] Dividing Array into k Segments

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.

👁 _Division-of-an-Array-to-Implement-k-Stacks

Limitation: This approach leads to inefficient space utilization, since one stack may become full even when other stacks still have free space available.


Output
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)

[Efficient Approach] Using Space Optimized Method

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:

  • An array top[] of size k, where top[i] stores the index of the top element of the i-th stack.
  • An array next[] of size n, which links free slots together and also helps connect elements within a stack.
  • A variable freeTop that stores the index of the first free slot in the array.

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:



Output
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:

Comment
Article Tags:
Article Tags: