ctci/03. Stacks and queues/3.1. 3stacks_in_array.md

1.7 KiB

3.1. Three in one

Describe how you could use a single array to implement three stacks.

I don't get the 3 stacks part.

Hints

1. Simulate one stack with an array, where the most recently added elements are removed first

Do I have to create a custom array? Something like this:

List<String> list = new ArrayList<int>(); // or LinkedList<String>();
list.add(2);
// add lots of stuff
list.remove(0);

2. We could allocate the first third to first stack, second third to second stack, and final third to last stack. But some stacks might be bigger than others, how to be more flexible with the divisions?*

Create list dynamically with the stacks?

3. If you want to allow for flexible divisions, you can shift stacks around. Can you ensure that all available capacity is used?*

I'm lost.

4. Think about the array as circular, such that the end of the array 'wraps around' to the start of the array

Solution

1. Approach 1: fixed divisions

Divide the array in 3 equal parts and allow the individual stack to grow in that limited space

  • Stack 1: [0. n/3)
  • Stack 2: [n/3. 2n/3)
  • Stack 2: [2n/3. n)

Code can be found on the official CTCI repository in Github.

2. Approach 2: flexible divisions

When one stack exceeds its initial capacity, grow the allowable capacity and shift elements as necessary. The design also includes a circular array so that the final stack might start at the end of the array and wrap around to the beginning.

Code can be found on the repo as before.