Context: I'm a CS n00b working my way through "Cracking the Coding Interview." The first problem asks to "implement an algorithm to determine if a string has all unique characters." My (likely naive) implementation is as follows:
def isUniqueChars2(string):
uchars = []
for c in string:
if c in uchars:
return False
else:
uchars.append(c)
return True
The author suggests the following implementation:
def isUniqueChars(string):
checker = 0
for c in string:
val = ord(c) - ord('a')
if (checker & (1 << val) > 0):
return False
else:
checker |= (1 << val)
return True
What makes the author's implementation better than mine (FWIW, the author's solution was in Java and I converted it to Python -- is my solution one that is not possible to implement in Java)? Or, more generally, what is desirable in a solution to this problem? What is wrong with the approach I've taken? I'm assuming there are some fundamental CS concepts (that I'm not familiar with) that are important and help inform the choice of which approach to take to this problem.
dict
, especially if the variable in question isn't even a dict! – Scroopset
rather than alist
, forO(1)
lookup. It's slower than the author's code, but far more Pythonic (presumably why the author's code wasn't written in Python...) – Scroopdict
touchars
. May I suggest you revert this change, since several comments refer to this mistake, and several replies have already addressed your actual question? Changing the question underneath just makes things confusing to new visitors. – Donetsdict
touchars
. I had originally used a dictionary instead of a list. – Knoxville