DEV Community

Discussion on: Whiteboarding in Python: Can You Solve This Simple String Problem?

Collapse
 
niconanitori profile image
Rain Gibson • Edited

Awesome article! Here's a performance golf challenger. O(1) space complexity and O(n) runtime complexity like the dictionary solution, but it avoids the setup cost and hashing cost of a dictionary. It'll be a lot faster if we're checking many small strings. This is biased towards more bare-bones languages like C/++, but should work well for Python too. Of course, it assumes ASCII strings - the same solution for unicode would require too much space and a dictionary would be faster in that case.

def isUnique(string):
    seenLetter = [False]*256 # list of bools for every ascii character/code
    for letter in string:
        ordinalValue = ord(letter) # ascii value. In C you could just use the char as an index directly.
        if seenLetter[ordinalValue]:
            return False
        seenLetter[ordinalValue] = True
    return True

# tests
for string in ["abcd","aa","0asdferytyu0","qwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()"]:
    print(isUnique(string), string)
Enter fullscreen mode Exit fullscreen mode