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 11 | System Design <strong>and</strong> Memory Limits<br />

this case?<br />

Usually, in BFS, we mark a node as visited by setting a flag visited in its node class. Here, we<br />

don’t want to do that (<strong>the</strong>re could be multiple searches going on at <strong>the</strong> same time, so it’s bad<br />

to just edit our data). In this case, we could mimic <strong>the</strong> marking of nodes with a hash table to<br />

lookup a node id <strong>and</strong> whe<strong>the</strong>r or not it’s been visited.<br />

O<strong>the</strong>r Follow-Up <strong>Questions</strong>:<br />

»»<br />

In <strong>the</strong> real world, servers fail. How does this affect you?<br />

»»<br />

How could you take advantage of caching?<br />

»»<br />

Do you search until <strong>the</strong> end of <strong>the</strong> graph (infinite)? How do you decide when to give up?<br />

»»<br />

In real life, some people have more friends of friends than o<strong>the</strong>rs, <strong>and</strong> are <strong>the</strong>refore<br />

more likely to make a path between you <strong>and</strong> someone else. How could you use this data<br />

to pick where you start traversing?<br />

The following code demonstrates our algorithm:<br />

1 public class Server {<br />

2 ArrayList machines = new ArrayList();<br />

3 }<br />

4<br />

5 public class Machine {<br />

6 public ArrayList persons = new ArrayList();<br />

7 public int machineID;<br />

8 }<br />

9<br />

10 public class Person {<br />

11 private ArrayList friends;<br />

12 private int ID;<br />

13 private int machineID;<br />

14 private String info;<br />

15 private Server server = new Server();<br />

16<br />

17 public String getInfo() { return info; }<br />

18 public void setInfo(String info) {<br />

19 this.info = info;<br />

20 }<br />

21<br />

22 public int[] getFriends() {<br />

23 int[] temp = new int[friends.size()];<br />

24 for (int i = 0; i < temp.length; i++) {<br />

25 temp[i] = friends.get(i);<br />

26 }<br />

27 return temp;<br />

28 }<br />

CareerCup.com<br />

2 0 0

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

Saved successfully!

Ooh no, something went wrong!