The problem asks us to implement a function called “isUnique” which will return True or False as to whether a string contains all unique characters.
One approach is to use a Boolean array while the other uses a HashTable.
In Python we get this for the Boolean array:
def is_unique(str):
# Assuming character set is ASCII (128 characters)
if len(string) > 128:
return False
char_set = [False] * 128
for char in string:
val = ord(char)
if char_set[val]:
return False
char_set[val] = True
return True
And this using a dictionary/hash map:
def is_unique(str):
# Assuming character set is ASCII (128 characters)
if len(string) > 128:
return False
character_counts = {}
for char in string:
if char in character_counts:
return False
character_counts[char] = 1
return True
Personally I find the dictionary approach to be more intuitive, but the book gives the former solution along with a bitwise approach.
So, is there any sense in using one over the other if it came up in an interview, or perhaps it’s just useful to talk about the different options available. Although, I still don’t know how much discernment can be made between the two.
Edit: To be clear, I’m just wondering if there are any noticeable pro’s and con’s between using the Boolean array versus a hash map. Or are they essentially identical given any situation?