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 2 How would you design a stack which, in addition to push and pop, also has a function<br />

min which returns <strong>the</strong> minimum element? Push, pop and min should all operate in<br />

O(1) time<br />

SOLUTION<br />

1 1 3<br />

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

pg 52<br />

You can implement this by having each node in <strong>the</strong> stack keep track of <strong>the</strong> minimum beneath<br />

itself Then, to find <strong>the</strong> min, you just look at what <strong>the</strong> top element thinks is <strong>the</strong> min<br />

When you push an element onto <strong>the</strong> stack, <strong>the</strong> element is given <strong>the</strong> current minimum It sets<br />

its “local min” to be <strong>the</strong> min<br />

1 public class StackWithMin extends Stack {<br />

2 public void push(int value) {<br />

3 int newMin = Math.min(value, min());<br />

4 super.push(new NodeWithMin(value, newMin));<br />

5 }<br />

6<br />

7 public int min() {<br />

8 if (this.isEmpty()) {<br />

9 return Integer.MAX_VALUE;<br />

10 } else {<br />

11 return peek().min;<br />

12 }<br />

13 }<br />

14 }<br />

15<br />

16 class NodeWithMin {<br />

17 public int value;<br />

18 public int min;<br />

19 public NodeWithMin(int v, int min){<br />

20 value = v;<br />

21 this.min = min;<br />

22 }<br />

23 }<br />

There’s just one issue with this: if we have a large stack, we waste a lot of space by keeping<br />

track of <strong>the</strong> min for every single element Can we do better?<br />

We can (maybe) do a bit better than this by using an additional stack which keeps track of<br />

<strong>the</strong> mins<br />

1 public class StackWithMin2 extends Stack {<br />

2 Stack s2;<br />

3 public StackWithMin2() {<br />

4 s2 = new Stack();

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

Saved successfully!

Ooh no, something went wrong!