How to implement three stacks using a single array

后端 未结 17 767
情书的邮戳
情书的邮戳 2020-12-23 15:10

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

17条回答
  •  梦毁少年i
    2020-12-23 15:46

    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.

提交回复
热议问题