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.
defisUnique(string):seenLetter=[False]*256# list of bools for every ascii character/code
forletterinstring:ordinalValue=ord(letter)# ascii value. In C you could just use the char as an index directly.
ifseenLetter[ordinalValue]:returnFalseseenLetter[ordinalValue]=TruereturnTrue# tests
forstringin["abcd","aa","0asdferytyu0","qwertyuiopasdfghjklzxcvbnm1234567890!@#$%^&*()"]:print(isUnique(string),string)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.