Implement k stacks in an array
Given an array of size n, the task is to implement k stacks using a single array. We mainly need to perform the following type of queries on the stack.
push(x, i) : This operations pushes the element x into stack i
pop(i) : This operation pops the top of stack iHere i varies from 0 to k-1
Naive Approach - Dividing Array into k Segments
The idea is to divide the array of size n into k equal segments, each of size n/k. Each segment acts as a dedicated space for one of the k stacks. We maintain k different top pointers (top[0] through top[k-1]), one for each stack, and initialize them to point to the start of their respective segments minus 1 (to indicate empty stacks). When pushing an element to stack i, we increment top[i] and place the element at that index. For popping from stack i, we return the element at top[i] and decrement top[i].
The main drawback is that it allocates a fixed amount of space for each stack regardless of their actual usage. If one stack requires more space than its allocated n/k elements while another stack is mostly empty, we still can't use the empty space from one stack for the overflow of another. This leads to "internal fragmentation" where some stacks might overflow even though there's plenty of unused space in the array overall, making poor use of the available memory.

#include <bits/stdc++.h>
using namespace std;
class kStacks {
private:
vector<int> arr;
int n, k;
vector<int> top;
vector<int> next;
int freeIndex;
public:
kStacks(int n, int k) {
this->n = n;
this->k = k;
arr.resize(n);
top.resize(k, -1);
next.resize(n);
// Initialize all spaces as free
freeIndex = 0;
for (int i = 0; i < n - 1; i++) {
next[i] = i + 1;
}
next[n - 1] = -1;
}
// Function to push element x into m'th stack
bool push(int x, int m) {
// Check if there is space available in the stack
if (freeIndex == -1) {
return false;
}
// Get the index of the free space
int i = freeIndex;
// Update freeIndex to the next free slot
freeIndex = next[i];
// Insert the element into the correct stack
next[i] = top[m];
top[m] = i;
arr[i] = x;
return true;
}
// Function to pop top element from m'th stack
int pop(int m) {
if (top[m] == -1) {
return -1;
}
// Get the top element from stack m
int i = top[m];
// Update the top of stack m
top[m] = next[i];
// Return the popped element and update the freeIndex
next[i] = freeIndex;
freeIndex = i;
return arr[i];
}
};
int main() {
int n = 5, k = 4;
kStacks* s = new kStacks(n, k);
vector<vector<int>> queries = {
{1, 15, 0},
{1, 25, 1},
{1, 35, 2},
{1, 45, 3},
{1, 55, 0},
{2, 0},
{2, 1},
{1, 55, 0},
{2, 3}
};
for (auto q : queries) {
if (q[0] == 1) {
if (s->push(q[1], q[2])) {
cout << 1 << " ";
} else {
cout << 0 << " ";
}
} else {
cout << s->pop(q[1]) << " ";
}
}
return 0;
}
import java.util.*;
class kStacks {
private int[] arr;
private int[] top;
private int[] next;
private int freeIndex;
private int n, k;
public kStacks(int n, int k) {
this.n = n;
this.k = k;
arr = new int[n];
top = new int[k];
next = new int[n];
// Initialize all stacks as empty
Arrays.fill(top, -1);
freeIndex = 0;
for (int i = 0; i < n - 1; i++) {
next[i] = i + 1;
}
next[n - 1] = -1;
}
// Function to push element x into m'th stack
public boolean push(int x, int m) {
// Check if there is space available in the stack
if (freeIndex == -1) {
return false;
}
// Get the index of the free space
int i = freeIndex;
// Update freeIndex to the next free slot
freeIndex = next[i];
// Insert the element into the correct stack
next[i] = top[m];
top[m] = i;
arr[i] = x;
return true;
}
// Function to pop top element from m'th stack
public int pop(int m) {
// Check if the stack is empty
if (top[m] == -1) {
return -1;
}
// Get the top element from stack m
int i = top[m];
// Update the top of stack m
top[m] = next[i];
// Return the popped element and update the freeIndex
next[i] = freeIndex;
freeIndex = i;
return arr[i];
}
public static void main(String[] args) {
int n = 5, k = 4;
kStacks s = new kStacks(n, k);
int[][] queries = {
{1, 15, 0},
{1, 25, 1},
{1, 35, 2},
{1, 45, 3},
{1, 55, 0},
{2, 0},
{2, 1},
{1, 55, 0},
{2, 3}
};
for (int[] q : queries) {
if (q[0] == 1) {
if (s.push(q[1], q[2])) {
System.out.print(1 + " ");
} else {
System.out.print(0 + " ");
}
} else {
System.out.print(s.pop(q[1]) + " ");
}
}
}
}
class kStacks:
def __init__(self, n, k):
self.n = n
self.k = k
self.arr = [0] * n
self.top = [-1] * k
self.next = list(range(1, n)) + [-1]
self.freeIndex = 0
# Function to push element x into m'th stack
def push(self, x, m):
# Check if there is space available in the stack
if self.freeIndex == -1:
return False
# Get the index of the free space
i = self.freeIndex
# Update freeIndex to the next free slot
self.freeIndex = self.next[i]
# Insert the element into the correct stack
self.next[i] = self.top[m]
self.top[m] = i
self.arr[i] = x
return True
# Function to pop top element from m'th stack
def pop(self, m):
# Check if the stack is empty
if self.top[m] == -1:
return -1
# Get the top element from stack m
i = self.top[m]
# Update the top of stack m
self.top[m] = self.next[i]
# Return the popped element and update the freeIndex
self.next[i] = self.freeIndex
self.freeIndex = i
return self.arr[i]
if __name__ == '__main__':
n = 5
k = 4
s = kStacks(n, k)
queries = [
[1, 15, 0],
[1, 25, 1],
[1, 35, 2],
[1, 45, 3],
[1, 55, 0],
[2, 0],
[2, 1],
[1, 55, 0],
[2, 3]
]
for q in queries:
if q[0] == 1:
if s.push(q[1], q[2]):
print(1, end=' ')
else:
print(0, end=' ')
else:
print(s.pop(q[1]), end=' ')
using System;
using System.Collections.Generic;
class kStacks {
private List<int> arr;
private List<int> top;
private List<int> next;
private int freeIndex;
public kStacks(int n, int k) {
arr = new List<int>(new int[n]);
top = new List<int>(new int[k]);
next = new List<int>(new int[n]);
// Initialize all spaces as free
freeIndex = 0;
for (int i = 0; i < n - 1; i++) {
next[i] = i + 1;
}
next[n - 1] = -1;
}
// Function to push element x into m'th stack
public bool Push(int x, int m) {
// Check if there is space available in the stack
if (freeIndex == -1) {
return false;
}
// Get the index of the free space
int i = freeIndex;
// Update freeIndex to the next free slot
freeIndex = next[i];
// Insert the element into the correct stack
next[i] = top[m];
top[m] = i;
arr[i] = x;
return true;
}
// Function to pop top element from m'th stack
public int Pop(int m) {
// Check if the stack is empty
if (top[m] == -1) {
return -1; // Stack is empty
}
// Get the top element from stack m
int i = top[m];
// Update the top of stack m
top[m] = next[i];
// Return the popped element and update the freeIndex
next[i] = freeIndex;
freeIndex = i;
return arr[i];
}
}
class Program {
static void Main() {
int n = 5, k = 4;
kStacks s = new kStacks(n, k);
List<List<int>> queries = new List<List<int>>() {
new List<int> {1, 15, 0},
new List<int> {1, 25, 1},
new List<int> {1, 35, 2},
new List<int> {1, 45, 3},
new List<int> {1, 55, 0},
new List<int> {2, 0},
new List<int> {2, 1},
new List<int> {1, 55, 0},
new List<int> {2, 3}
};
foreach (var q in queries) {
if (q[0] == 1) {
Console.Write((s.Push(q[1], q[2]) ? 1 : 0) + " ");
} else {
Console.Write(s.Pop(q[1]) + " ");
}
}
}
}
class kStacks {
constructor(n, k) {
this.n = n;
this.k = k;
this.arr = new Array(n);
this.top = new Array(k).fill(-1);
this.next = new Array(n);
this.freeIndex = 0;
// Initialize all spaces as free
for (let i = 0; i < n - 1; i++) {
this.next[i] = i + 1;
}
this.next[n - 1] = -1;
}
// Function to push element x into m'th stack
push(x, m) {
// Check if there is space available in the stack
if (this.freeIndex === -1) {
return false;
}
// Get the index of the free space
let i = this.freeIndex;
// Update freeIndex to the next free slot
this.freeIndex = this.next[i];
// Insert the element into the correct stack
this.next[i] = this.top[m];
this.top[m] = i;
this.arr[i] = x;
return true;
}
// Function to pop top element from m'th stack
pop(m) {
// Check if the stack is empty
if (this.top[m] === -1) {
return -1;
}
// Get the top element from stack m
let i = this.top[m];
// Update the top of stack m
this.top[m] = this.next[i];
// Return the popped element and update the freeIndex
this.next[i] = this.freeIndex;
this.freeIndex = i;
return this.arr[i];
}
}
let n = 5, k = 4;
let s = new kStacks(n, k);
let queries = [
[1, 15, 0],
[1, 25, 1],
[1, 35, 2],
[1, 45, 3],
[1, 55, 0],
[2, 0],
[2, 1],
[1, 55, 0],
[2, 3]
];
for (let q of queries) {
if (q[0] === 1) {
process.stdout.write((s.push(q[1], q[2]) ? 1 : 0) + " ");
} else {
process.stdout.write(s.pop(q[1]) + " ");
}
}
Output
1 1 1 1 0 15 25 1 45
Time Complexity:
- O(1) for push operation.
- O(1) for pop operation.
Auxiliary Space: O(n), where n is the size of array.
Efficient Approach - Using Space Optimized Method
The idea is to use a single array for storing elements of all stacks along with an auxiliary array that maintains pointers to the next element in each stack. Instead of dividing the array into fixed segments, we implement a free list structure that keeps track of available spaces in the array.
Following are the two extra arrays are used:
1) top[]:This is of size k and stores indexes of top elements in all stacks. top[i] = -1 indicates an empty stack.
2) next[]: This is of size n and stores indexes of next item for the items in array arr[]. For stack elements, it points to the next stack element index and for free index, it indicates the index of next free index.
Algorithm:
- Initialize an array
top
of size k to keep track of the top element of each stack. Set top[i] = -1 for all 0 ≤ i < k to indicate empty stacks. - Initialize an array
next
of size n to link elements in the same stack and maintain a free list. Set next[i] = i+1 for all 0 ≤ i < n-1, and next[n-1] = -1. - Initialize a variable
free = 0
to point to the first available position in the free list. - To push an element onto the m-th stack:
- Check if the array is full by checking if
free
is -1. If it is, return false. - Store the current
free
index, updatefree = next[free]
to point to the next available slot. - Link the new element to the current stack by setting
next[current_index] = top[m]
. - Update the top of the stack to the new element:
top[m] = current_index
. - Store the value in the array at the allocated position.
- Check if the array is full by checking if
- To pop an element from the m-th stack:
- Check if the stack is empty by checking if
top[m]
is -1. If it is, return -1. - Get the index of the top element:
i = top[m]
. - Update the top to the next element in the stack:
top[m] = next[i]
. - Return the element to the free list by setting
next[i] = free
andfree = i
. - Return the element value.
- Check if the stack is empty by checking if
// C++ program to implement k stacks in an array.
#include <bits/stdc++.h>
using namespace std;
class kStacks {
private:
vector<int> arr;
int n, k;
vector<int> top;
vector<int> next;
int freeIndex;
public:
// Constructor to initialize kStacks
kStacks(int n, int k) {
this->n = n;
this->k = k;
arr.resize(n);
top.resize(k, -1);
next.resize(n);
// Initialize all spaces as free
freeIndex = 0;
for (int i = 0; i < n-1; i++)
next[i] = i + 1;
// -1 is used to indicate end of free list
next[n-1] = -1;
}
// Function to push element x into
// m'th stack
bool push(int x, int m) {
// Check if we have space for a new element
if (freeIndex == -1) {
return false;
}
// Store index of first free slot
int i = freeIndex;
// Update free to point to next slot in free list
freeIndex = next[i];
// Update next of top and then top for stack m
next[i] = top[m];
top[m] = i;
// Store the item in array
arr[i] = x;
return true;
}
// Function to pop top element from
// m'th stack.
int pop(int m) {
// Check if stack is empty
if (top[m] == -1) {
return -1;
}
// Find index of top item in stack m
int i = top[m];
// Update top of stack m
top[m] = next[i];
// Add the previous top to free list
next[i] = freeIndex;
freeIndex = i;
// Return the popped element
return arr[i];
}
};
int main() {
int n = 5, k = 4;
kStacks* s = new kStacks(n, k);
// Each query is of either 2 types
// 1: Push operation -> {1, x, m}
// 2: Pop operation -> {2, m}
vector<vector<int>> queries = {
{1, 15, 0},
{1, 25, 1},
{1, 35, 2},
{1, 45, 3},
{1, 55, 0},
{2, 0},
{2, 1},
{1, 55, 0},
{2, 3}
};
for (auto q: queries) {
if (q[0] == 1) {
if (s->push(q[1], q[2])) {
cout << 1 << " ";
} else {
cout << 0 << " ";
}
}
else {
cout << s->pop(q[1]) << " ";
}
}
return 0;
}
// Java program to implement k stacks in an array.
import java.util.*;
class kStacks {
int[] arr;
int n, k;
int[] top;
int[] next;
int freeIndex;
// Constructor to initialize kStacks
kStacks(int n, int k) {
this.n = n;
this.k = k;
arr = new int[n];
top = new int[k];
next = new int[n];
Arrays.fill(top, -1);
// Initialize all spaces as free
freeIndex = 0;
for (int i = 0; i < n - 1; i++)
next[i] = i + 1;
// -1 is used to indicate end of free list
next[n - 1] = -1;
}
// Function to push element x into
// m'th stack
boolean push(int x, int m) {
// Check if we have space for a new element
if (freeIndex == -1) {
return false;
}
// Store index of first free slot
int i = freeIndex;
// Update free to point to next slot in free list
freeIndex = next[i];
// Update next of top and then top for stack m
next[i] = top[m];
top[m] = i;
// Store the item in array
arr[i] = x;
return true;
}
// Function to pop top element from
// m'th stack.
int pop(int m) {
// Check if stack is empty
if (top[m] == -1) {
return -1;
}
// Find index of top item in stack m
int i = top[m];
// Update top of stack m
top[m] = next[i];
// Add the previous top to free list
next[i] = freeIndex;
freeIndex = i;
// Return the popped element
return arr[i];
}
}
class GfG {
public static void main(String[] args) {
int n = 5, k = 4;
kStacks s = new kStacks(n, k);
// Each query is of either 2 types
// 1: Push operation -> {1, x, m}
// 2: Pop operation -> {2, m}
int[][] queries = {
{1, 15, 0},
{1, 25, 1},
{1, 35, 2},
{1, 45, 3},
{1, 55, 0},
{2, 0},
{2, 1},
{1, 55, 0},
{2, 3}
};
for (int[] q : queries) {
if (q[0] == 1) {
if (s.push(q[1], q[2])) {
System.out.print(1 + " ");
} else {
System.out.print(0 + " ");
}
} else {
System.out.print(s.pop(q[1]) + " ");
}
}
}
}
# Python program to implement k stacks in an array.
class kStacks:
# Constructor to initialize kStacks
def __init__(self, n, k):
self.n = n
self.k = k
self.arr = [0] * n
self.top = [-1] * k
self.next = [0] * n
# Initialize all spaces as free
self.freeIndex = 0
for i in range(n - 1):
self.next[i] = i + 1
# -1 is used to indicate end of free list
self.next[n - 1] = -1
# Function to push element x into
# m'th stack
def push(self, x, m):
# Check if we have space for a new element
if self.freeIndex == -1:
return False
# Store index of first free slot
i = self.freeIndex
# Update free to point to next slot in free list
self.freeIndex = self.next[i]
# Update next of top and then top for stack m
self.next[i] = self.top[m]
self.top[m] = i
# Store the item in array
self.arr[i] = x
return True
# Function to pop top element from
# m'th stack.
def pop(self, m):
# Check if stack is empty
if self.top[m] == -1:
return -1
# Find index of top item in stack m
i = self.top[m]
# Update top of stack m
self.top[m] = self.next[i]
# Add the previous top to free list
self.next[i] = self.freeIndex
self.freeIndex = i
# Return the popped element
return self.arr[i]
if __name__ == "__main__":
n, k = 5, 4
s = kStacks(n, k)
# Each query is of either 2 types
# 1: Push operation -> {1, x, m}
# 2: Pop operation -> {2, m}
queries = [
[1, 15, 0],
[1, 25, 1],
[1, 35, 2],
[1, 45, 3],
[1, 55, 0],
[2, 0],
[2, 1],
[1, 55, 0],
[2, 3]
]
for q in queries:
if q[0] == 1:
if s.push(q[1], q[2]):
print(1, end=" ")
else:
print(0, end=" ")
else:
print(s.pop(q[1]), end=" ")
// C# program to implement k stacks in an array.
using System;
using System.Collections.Generic;
class kStacks {
int[] arr;
int n, k;
int[] top;
int[] next;
int freeIndex;
// Constructor to initialize kStacks
public kStacks(int n, int k) {
this.n = n;
this.k = k;
arr = new int[this.n];
top = new int[this.k];
next = new int[this.n];
for (int i = 0; i < k; i++) top[i] = -1;
// Initialize all spaces as free
freeIndex = 0;
for (int i = 0; i < n - 1; i++)
next[i] = i + 1;
// -1 is used to indicate end of free list
next[n - 1] = -1;
}
// Function to push element x into
// m'th stack
public bool push(int x, int m) {
// Check if we have space for a new element
if (freeIndex == -1) {
return false;
}
// Store index of first free slot
int i = freeIndex;
// Update free to point to next slot in free list
freeIndex = next[i];
// Update next of top and then top for stack m
next[i] = top[m];
top[m] = i;
// Store the item in array
arr[i] = x;
return true;
}
// Function to pop top element from
// m'th stack.
public int pop(int m) {
// Check if stack is empty
if (top[m] == -1) {
return -1;
}
// Find index of top item in stack m
int i = top[m];
// Update top of stack m
top[m] = next[i];
// Add the previous top to free list
next[i] = freeIndex;
freeIndex = i;
// Return the popped element
return arr[i];
}
}
class GfG {
static void Main(string[] args) {
int n = 5, k = 4;
kStacks s = new kStacks(n, k);
// Each query is of either 2 types
// 1: Push operation -> {1, x, m}
// 2: Pop operation -> {2, m}
List<List<int>> queries = new List<List<int>> {
new List<int>{1, 15, 0},
new List<int>{1, 25, 1},
new List<int>{1, 35, 2},
new List<int>{1, 45, 3},
new List<int>{1, 55, 0},
new List<int>{2, 0},
new List<int>{2, 1},
new List<int>{1, 55, 0},
new List<int>{2, 3}
};
foreach (var q in queries) {
if (q[0] == 1) {
if (s.push(q[1], q[2])) {
Console.Write("1 ");
} else {
Console.Write("0 ");
}
} else {
Console.Write(s.pop(q[1]) + " ");
}
}
}
}
// JavaScript program to implement k stacks in an array.
class kStacks {
constructor(n, k) {
this.n = n;
this.k = k;
this.arr = new Array(n);
this.top = new Array(k).fill(-1);
this.next = new Array(n);
// Initialize all spaces as free
this.freeIndex = 0;
for (let i = 0; i < n - 1; i++) {
this.next[i] = i + 1;
}
// -1 is used to indicate end of free list
this.next[n - 1] = -1;
}
// Function to push element x into
// m'th stack
push(x, m) {
if (this.freeIndex === -1) {
return false;
}
let i = this.freeIndex;
this.freeIndex = this.next[i];
this.next[i] = this.top[m];
this.top[m] = i;
this.arr[i] = x;
return true;
}
// Function to pop top element from
// m'th stack.
pop(m) {
if (this.top[m] === -1) {
return -1;
}
let i = this.top[m];
this.top[m] = this.next[i];
this.next[i] = this.freeIndex;
this.freeIndex = i;
return this.arr[i];
}
}
let n = 5, k = 4;
let s = new kStacks(n, k);
// Each query is of either 2 types
// 1: Push operation -> {1, x, m}
// 2: Pop operation -> {2, m}
let queries = [
[1, 15, 0],
[1, 25, 1],
[1, 35, 2],
[1, 45, 3],
[1, 55, 0],
[2, 0],
[2, 1],
[1, 55, 0],
[2, 3]
];
for (let q of queries) {
if (q[0] === 1) {
process.stdout.write((s.push(q[1], q[2]) ? "1" : "0") + " ");
} else {
process.stdout.write(s.pop(q[1]) + " ");
}
}
Output
1 1 1 1 1 55 25 1 45
Time Complexity:
- O(1) for push operation.
- O(1) for pop operation.
Auxiliary Space: O(n), where n is the size of array.
Related Article: