views:

842

answers:

9

Hi,

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.

+1  A: 

First stack grows from left to right.

Second stack grows from right to left.

Third stack starts from the middle. Suppose odd sized array for simplicity. Then third stack grows like this:

* * * * * * * * * * *
      5 3 1 2 4

First and second stacks are allowed to grow maximum at the half size of array. The third stack can grow to fill in the whole array at a maximum.

Worst case scenario is when one of the first two arrays grows at 50% of the array. Then there is a 50% waste of the array. To optimise the efficiency the third array must be selected to be the one that grows quicker than the other two.

kgiannakakis
But that does not fit the requirements. Put in one element for the 3rd stack, then only elements for the 1st stack ... how will your solution handle that?
tanascius
But suppose 1st stack has 1 entry, 2nd stack has 4 entries. Where do you put 3rd stack's 4th entry?
Chris
Both of you are right. My solution can waste up to 50%. I will be interested to see if anyone can offer a better solution.
kgiannakakis
I wanted to mention this approach in my initial post. But as the author pointed that it could waste 50% space in the worst case.
A: 

first stack grows at 3n, second stack grows at 3n+1, third grows at 3n+2

for n={0...N}

Gunjan
You divide the array just in three parts ... what happens when only the 1st stack grows all the time?
tanascius
Doesn't fit requirements. Once the first stack has 1/3 as many entries as the array length, it overflows regardless of whether there's space in the array allotted for stacks 2 and 3.
Chris
@Gunjan: It might waste 2/3rd space in worst case.
+10  A: 

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 ^^).

tanascius
You can point stacks to "null"-indexes and have pointer to first free element in sequence of chained free elements. Each time you push to stack you get that element from sequence of free elements and changes next pointer of it to old stack-top. When element is popped out of stack it returns to head of free sequence. And kgiannakakis wastes _up to 50%_ and your variant spends _50% always_ for pointer.
ony
The question doesn't say what type the array is or the values you need to store. If you assumed your stack has to store 32-bit numbers and you create an array of 64-bit numbers you could easily pack the linked-list pointers into the upper/lower bits of each array value.
Paolo
@Paolo: yes it depends on the specification - you always need some space for your pointers. But my point is that a *doubly-linked list* is basically an adequate data structure for this problem. You you use it the implementation isn't difficult anymore.
tanascius
@tanascius Why the "double" links? A stack is always traversed in the same direction ...
belisarius
@belisarius: You are right. The idea is to use a 4th pointer for a list of free elements. I updated my answer ... ^^ thx
tanascius
@tanascius Ok. So you could implement four "stacks" for simplicity. A PUSH to any "real" stack needs a previous POP from the "free" stack. So you only implement two primitives (push, pop) for the whole problem. (i.e. no special treatment for the free list)
belisarius
+1  A: 

This is an interesting conundrum, and I don't have a real answer but thinking slightly outside the box...

it could depend on what each element in the stack consists of. If it's three stacks of true/false flags, then you could use the first three bits of integer elements. Ie. bit 0 is the value for the first stack, bit 1 is the value for the second stack, bit 2 is the value for the third stack. Then each stack can grow independently until the whole array is full for that stack. This is even better as the other stacks can also continue to grow even when the first stack is full.

I know this is cheating a bit and doesn't really answer the question but it does work for a very specific case and no entries in the stack are wasted. I am watching with interest to see whether anyone can come up with a proper answer that works for more generic elements.

gillez
You'll have waste of bit-sized elements instead of waste of any-sized elements. That's variant of splitting array in 3 parts but in this case with using interleaving.
ony
True and well spotted, so back to the think-tank. As Damien said, it depends on whether all array positions should be used to store values. If so, then the doubly-linked-list method (which is probably the correct answer, from an interview POV) can't be used. In this case kgiannakakis answer is probably ok, but obviously wastes up to 50% of the space. We're still waiting for a definitive answer that uses every element for a value and doesn't waste any space. Damien's does, but would be difficult to maintain order of the stack when moving from one end of the middle stack to the other.
gillez
A: 

Assuming that all array positions should be used to store values - I guess it depends on your definition of efficiency.

If you do the two stack solution, place the third stack somewhere in the middle, and track both its bottom and top, then most operations will continue to be efficient, at a penalty of an expensive Move operation (of the third stack towards wherever free space remains, moving to the half way point of free space) whenever a collision occurs.

It's certainly going to be quick to code and understand. What are our efficiency targets?

Damien_The_Unbeliever
+2  A: 

Split array in any 3 parts (no matter if you'll split it sequentially or interleaved). If one stack grows greater than 1/3 of array you start filling ends of rest two stacks from the end.

aaa bbb ccc
1   2   3
145 2   3
145 2 6 3
145 2 6 3 7
145 286 3 7
145 286 397

The worse case is when two stacks grows up to 1/3 boundary and then you have 30% of space waste.

ony
I couldn't grasp your idea completely. Did you mean, when first stack (marked with 'aaa') is filled up, say from LEFT to RIGHT, you'll insert elements in second stack space (marked with 'bbb') from RIGHT to LEFT. Similarly for second stack, you'll use third stack's space (marked with 'ccc'); and for third stack you'll use first stack's space.I believe it works with the penalty of 1/3rd space wastage.
When "aaa" is filled completely from LEFT to RIGHT it starts filling "bbb" and "ccc" simultaneously (odd element goes to one stack and even to other) from RIGHT to LEFT until it will met one of their top. I.e. length of stack for "aaa" is (n + (n- max (top("bbb"), top("ccc"))). When you hit problem with adding another element to stack "aaa" that means that array for "bbb" or for "ccc" is filled completely. So if all stacks grows with the same speed or one stack grows with speed 2x or two with 0x than no space is wasted. If there is one stack 2x and other 0x - you'll get (1/3)/2 space wasted.
ony
A: 

Yet another approach (as additional to linked-list) is to use map of stacks. In that case you'll have to use additional log(3^n)/log(2) bits for building map of data distribution in your n-length array. Each of 3-value part of map says which stack is owns next element. Ex. a.push(1); b.push(2); c.push(3); a.push(4); a.push(5); will give you image

aacba
54321

appropriate value of map is calculated while elements is pushed onto stack (with shifting contents of array)

map0 = any
map1 = map0*3 + 0
map2 = map1*3 + 1
map3 = map2*3 + 2
map4 = map3*3 + 0
map5 = map4*3 + 0 = any*3^5 + 45

and length of stacks 3,1,1
Once you'll want to do c.pop() you'll have to reorganize your elements by finding actual position of c.top() in original array through walking in cell-map (i.e. divide by 3 while mod by 3 isn't 2) and then shift all contents in array back to cover that hole. While walking through cell-map you'll have to store all position you have passed (mapX) and after passing that one which points to stack "c" you'll have to divide by 3 yet another time and multiply it by 3^(amount positions passed-1) and add mapX to get new value of cells-map.
Overhead for that fixed and depends on size of stack element (bits_per_value):
(log(3**n)/log(2)) / (n*log(bits_per_value)/log(2)) = log(3**n) / (n*log(bits_per_value)) = log(3) / log(bits_per_value)
So for bits_per_value = 32 it will be 31.7% space overhead and with growing bits_per_value it will decay (i.e. for 64 bits it will be 26.4%).

ony
+2  A: 

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.

Dimitris Andreou
Heh, whoever downvoted Knuth's reference, don't be ashamed, reveal yourself :)
Dimitris Andreou
By the way, the best answers given are already subsumed in Knuth's much more thorough treatment of this problem. Just sayin'.
Dimitris Andreou
Perhaps that person was not downvoting Knuth, but an answer that is basically useless if you do not already have the book at home (in which case you would not be interested in the question in the first place, I guess).
Pascal Cuoq
How about libraries. I can't remember the last time when I lived at a place without a library having Knuth in it.
Dimitris Andreou
A: 

We can use long bit array representing to which stack the i-th array cell belongs to. We can take values by modulo 3 (00 - empty, 01 - A, 10 - B, 11 - C). It would take N/2 bits or N/4 bytes of additional memory for N sized array.

For example for 1024 long int elements (4096 bytes) it would take only 256 bytes or 6%.

This bit array map can be placed in the same array at the beginning or at the end, just shrinking the size of the given array by constant 6%!

Vitamon