Sometimes, I come across the following interview question: How to implement 3 stacks with one array ? Of course, any static allocation is not a solution.
This is a very common interview question "Implement 3 stacks using a single Array or >List". Here is my solution-
Approach 1- Go for a fixed division of an array means if we divide our array into 3 equal parts and push the elements of an array into three fixed-sized stacks. For stack 1, use [0,n/3] For stack 2, use [n/3,2n/3] For stack 3, use [2n/3,n]. The problem with this approach is that we may face a condition where the size of an array may be greater than the size of the stack ie. Stack Overflow condition. So, we must take care of special cases and edge cases like this. now go for 2nd approach.
Approach 2- Flexible Division, In the first approach we face a condition where the size of an array may be greater than the size of the stack ie the Stack overflow condition. we can overcome this problem by doing a flexible division of the stack. while adding elements to the stack, when one stack exceeds the initial capacity, shift the elements to the next stack. So, this way we can approach this problem.