How To Implement two stacks in a single array

In this post, we will discuss how to efficiently implement two stacks in a single array.

 
A simple solution would be to divide the array in two halves and allocate each half for implementing two stacks. In other words, if given an array A of size n, the solution would allocate A[0,n/2] memory for 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 stack overflow exception even if other half has space available.
 
To handle this we can grow stack 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 size of the array. 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.
 
Below is C++ and Java implementation of the idea:
Output:

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


Learn More :