The Naive Approach
You could divide the array strictly in half (indices 0 to N/2 for Stack 1, and N/2 to N for Stack 2). But if Stack 1 gets full while Stack 2 is completely empty, you throw an Overflow error despite having empty space.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
How can you efficiently implement two separate stacks within a single statically sized array? The trick is to start at opposite ends and grow inwards.
You could divide the array strictly in half (indices 0 to N/2 for Stack 1, and N/2 to N for Stack 2). But if Stack 1 gets full while Stack 2 is completely empty, you throw an Overflow error despite having empty space.
Initialize `top1 = -1` and `top2 = size`. Stack 1 grows left-to-right. Stack 2 grows right-to-left. This way, no space is wasted. You only overflow when the two pointers collide.
The stacks are completely full ONLY when `top2 - top1 == 1`. At this exact moment, there are zero empty slots between them.