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 9 | Sorting <strong>and</strong> Searching<br />

9.5 Given a sorted array of strings which is interspersed with empty strings, write a method<br />

to find <strong>the</strong> location of a given string.<br />

Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4<br />

Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1<br />

SOLUTION<br />

pg 66<br />

Use ordinary binary search, but when you hit an empty string, advance to <strong>the</strong> next nonempty<br />

string; if <strong>the</strong>re is no next non-empty string, search <strong>the</strong> left half.<br />

1 public int search(String[] strings, String str, int first, int last) {<br />

2 while (first 1;<br />

11 while (strings[mid] == “”) {<br />

12 ++mid; // will always find one<br />

13 }<br />

14 int r = strings[mid].compareTo(str);<br />

15 if (r == 0) return mid;<br />

16 if (r < 0) {<br />

17 first = mid + 1;<br />

18 } else {<br />

19 last = mid - 1;<br />

20 }<br />

21 }<br />

22 return -1;<br />

23 }<br />

24<br />

25 public int search(String[] strings, String str) {<br />

26 if (strings == null || str == null) return -1;<br />

27 if (str == “”) {<br />

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

29 if (strings[i] == “”) return i;<br />

30 }<br />

31 return -1;<br />

32 }<br />

33 return search(strings, str, 0, strings.length - 1);<br />

34 }<br />

1 8 3<br />

<strong>Cracking</strong> <strong>the</strong> <strong>Coding</strong> <strong>Interview</strong> | Concepts <strong>and</strong> Algorithms

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

Saved successfully!

Ooh no, something went wrong!