This post will discuss how to implement two stacks in a single array efficiently.

A simple solution would be to divide the array into two halves and allocate each half to implement two stacks. In other words, for an array A of size n, the solution would allocate A[0, n/2] memory for the first stack and A[n/2+1, n-1] memory for the second stack. The problem with this approach is that it doesn’t efficiently utilize the available space in the array. For instance, if one half of the array is full, any subsequent push operations would lead to a stack overflow exception even though the other half has space available.

 
To handle this, we can grow stacks from two extreme corners of the array. In other words, the first stack grows from the 0'th index, and the second stack grows from the (n-1)'th index, where n is the array size. Both stacks can grow towards each other with no fixed capacity. Now overflow will only happen if both stacks are full (i.e., top elements of both stacks are adjacent), and there is no space left in the array to accommodate a new element.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

Popping element from the first stack: 5
Popping element from the second stack: 10

Java


Download  Run Code

Output:

Popping element from the first stack: 5
Popping element from the second stack: 10

Python


Download  Run Code

Output:

Popping element from the first stack: 5
Popping element from the second stack: 10

The time complexity of all stack operations is constant, i.e., O(1).