25.03.2013 Views

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

Cracking the Coding Interview - Fooo

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

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

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

SOLUTION<br />

Approach 1:<br />

1 1 1<br />

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

pg 52<br />

Divide <strong>the</strong> array in three equal parts and 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 />

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

» for stack 2, we will use [n/3, 2n/3)<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 and 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, and<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 }

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

Saved successfully!

Ooh no, something went wrong!