Problem Implement 3 stacks in 1 array
Solution Method 1 - Create 3 Stacks with Fixed Max Size Divide the array in three equal parts and allow the individual stack to grow in that limited space (note: [ means inclusive, while ( means exclusive of the end point).
for stack 1, we will use [0, n/3) for stack 2, we will use [n/3, 2n/3) for stack 3, we will use [2n/3, n) Code Java int stackSize = 300; int[] buffer = new int[stackSize * 3]; int[] stackPointer = {0,0,0}; // stack pointers to track top element void push(int stackNum, int value) { /* Find the index of the top element in the array + 1, and increment the stack pointer */ int index = stackNum * stackSize + stackPointer[stackNum] + 1; stackPointer[stackNum]++; buffer[index] = value; } int pop(int stackNum) { int index = stackNum * stackSize + stackPointer[stackNum]; stackPointer[stackNum]--; int value = buffer[index]; buffer[index] = 0; return value; } int peek(int stackNum) { int index = stackNum * stackSize + stackPointer[stackNum]; return buffer[index]; } boolean isEmpty(int stackNum) { return stackPointer[stackNum] == stackNum * stackSize; } ...