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

Create successful ePaper yourself

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

<strong>Solutions</strong> to Chapter 1 | Arrays <strong>and</strong> Strings<br />

1.1 Implement an algorithm to determine if a string has all unique characters. What if<br />

you can not use additional data structures?<br />

SOLUTION<br />

pg 48<br />

For simplicity, assume char set is ASCII (if not, we need to increase <strong>the</strong> storage size. The rest<br />

of <strong>the</strong> logic would be <strong>the</strong> same). NOTE: This is a great thing to point out to your interviewer!<br />

1 public static boolean isUniqueChars2(String str) {<br />

2 boolean[] char_set = new boolean[256];<br />

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

4 int val = str.charAt(i);<br />

5 if (char_set[val]) return false;<br />

6 char_set[val] = true;<br />

7 }<br />

8 return true;<br />

9 }<br />

Time complexity is O(n), where n is <strong>the</strong> length of <strong>the</strong> string, <strong>and</strong> space complexity is O(n).<br />

We can reduce our space usage a little bit by using a bit vector. We will assume, in <strong>the</strong> below<br />

code, that <strong>the</strong> string is only lower case ‘a’ through ‘z’. This will allow us to use just a single int<br />

1 public static boolean isUniqueChars(String str) {<br />

2 int checker = 0;<br />

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

4 int val = str.charAt(i) - ‘a’;<br />

5 if ((checker & (1 0) return false;<br />

6 checker |= (1

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

Saved successfully!

Ooh no, something went wrong!