Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement three stacks using a single array

I came across this problem in an interview website. The problem asks for efficiently implement three stacks in a single array, such that no stack overflows until there is no space left in the entire array space.

For implementing 2 stacks in an array, it's pretty obvious: 1st stack grows from LEFT to RIGHT, and 2nd stack grows from RIGHT to LEFT; and when the stackTopIndex crosses, it signals an overflow.

Thanks in advance for your insightful answer.

like image 473
user369070 Avatar asked Jun 17 '10 08:06

user369070


People also ask

How can we implement multiple stacks using a single array?

Method 1 (Divide the array in slots of size n/k) A simple way to implement k stacks is to divide the array in k slots of size n/k each, and fix the slots for different stacks, i.e., use arr[0] to arr[n/k-1] for first stack, and arr[n/k] to arr[2n/k-1] for stack2 where arr[] is the array to be used to implement two ...

Can you implement a stack using an array?

A stack data structure can be implemented using a one-dimensional array. But stack implemented using array stores only a fixed number of data values.


2 Answers

You can implement three stacks with a linked list:

  • You need a pointer pointing to the next free element. Three more pointers return the last element of each stack (or null, if the stack is empty).
  • When a stack gets another element added, it has to use the first free element and set the free pointer to the next free element (or an overflow error will be raised). Its own pointer has to point to the new element, from there back to the next element in the stack.
  • When a stack gets an element removed it will hand it back into the list of free elements. The own pointer of the stack will be redirected to the next element in the stack.

A linked list can be implemented within an array.

How (space) efficent is this?
It is no problem to build a linked list by using two cells of an array for each list element (value + pointer). Depending on the specification you could even get pointer and value into one array element (e.g. the array is long, value and pointer are only int).
Compare this to the solution of kgiannakakis ... where you lose up to 50% (only in the worst case). But I think that my solution is a bit cleaner (and maybe more academic, which should be no disadvantage for an interview question ^^).

like image 182
tanascius Avatar answered Sep 19 '22 15:09

tanascius


See Knuth, The Art of Computer Programming, Volume 1, Section 2.2.2. titled "Sequential allocation". Discusses allocating multiple queues/stacks in a single array, with algorithms dealing with overflows, etc.

like image 45
Dimitris Andreou Avatar answered Sep 20 '22 15:09

Dimitris Andreou