27.10.2014 Views

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

Cracking the Coding Interview, 4 Edition - 150 Programming Interview Questions and Solutions

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Solutions</strong> to Chapter 3 | Stacks <strong>and</strong> Queues<br />

3.1 Describe how you could use a single array to implement three stacks.<br />

pg 52<br />

SOLUTION<br />

Approach 1:<br />

Divide <strong>the</strong> array in three equal parts <strong>and</strong> allow <strong>the</strong> individual stack to grow in that limited<br />

space (note: “[“ means inclusive, while “(“ means exclusive of <strong>the</strong> end point).<br />

»»<br />

for stack 1, we will use [0, n/3)<br />

»»<br />

for stack 2, we will use [n/3, 2n/3)<br />

»»<br />

for stack 3, we will use [2n/3, n)<br />

This solution is based on <strong>the</strong> assumption that we do not have any extra information about<br />

<strong>the</strong> usage of space by individual stacks <strong>and</strong> that we can’t ei<strong>the</strong>r modify or use any extra<br />

space. With <strong>the</strong>se constraints, we are left with no o<strong>the</strong>r choice but to divide equally.<br />

1 int stackSize = 300;<br />

2 int[] buffer = new int [stackSize * 3];<br />

3 int[] stackPointer = {0, 0, 0}; // stack pointers to track top elem<br />

4<br />

5 void push(int stackNum, int value) {<br />

6 /* Find <strong>the</strong> index of <strong>the</strong> top element in <strong>the</strong> array + 1, <strong>and</strong><br />

7 * increment <strong>the</strong> stack pointer */<br />

8 int index = stackNum * stackSize + stackPointer[stackNum] + 1;<br />

9 stackPointer[stackNum]++;<br />

10 buffer[index] = value;<br />

11 }<br />

12<br />

13 int pop(int stackNum) {<br />

14 int index = stackNum * stackSize + stackPointer[stackNum];<br />

15 stackPointer[stackNum]--;<br />

16 int value = buffer[index];<br />

17 buffer[index]=0;<br />

18 return value;<br />

19 }<br />

20<br />

21 int peek(int stackNum) {<br />

22 int index = stackNum * stackSize + stackPointer[stackNum];<br />

23 return buffer[index];<br />

24 }<br />

25<br />

26 boolean isEmpty(int stackNum) {<br />

27 return stackPointer[stackNum] == stackNum*stackSize;<br />

28 }<br />

1 1 1<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Data Structures

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!