Python Program to Check if String Has All Unique Characters
len(set(string)) == len(string), which compares the length of the string to the length of the set of its characters.Examples
How to Think About It
Algorithm
Code
def has_all_unique_chars(s: str) -> bool: return len(set(s)) == len(s) # Example usage print(has_all_unique_chars('hello')) # Output: False print(has_all_unique_chars('world')) # Output: True print(has_all_unique_chars('')) # Output: True
Dry Run
Let's trace the string 'hello' through the code
Input string
s = 'hello'
Convert to set
set(s) = {'h', 'e', 'l', 'o'}
Compare lengths
len(set(s)) = 4, len(s) = 5
Return result
4 == 5 is False, so return False
| Iteration | Set Content | Set Length | String Length | Result |
|---|---|---|---|---|
| 1 | {'h', 'e', 'l', 'o'} | 4 | 5 | False |
Why This Works
Step 1: Using a set to find unique characters
A set automatically removes duplicate characters, so converting the string to a set keeps only unique characters.
Step 2: Comparing lengths
If the length of the set equals the length of the original string, it means no characters were removed, so all are unique.
Step 3: Return boolean result
The comparison returns True if all characters are unique, otherwise False.
Alternative Approaches
def has_all_unique_chars(s: str) -> bool: seen = set() for char in s: if char in seen: return False seen.add(char) return True print(has_all_unique_chars('hello')) # False print(has_all_unique_chars('world')) # True
def has_all_unique_chars(s: str) -> bool: sorted_s = sorted(s) for i in range(len(sorted_s) - 1): if sorted_s[i] == sorted_s[i + 1]: return False return True print(has_all_unique_chars('hello')) # False print(has_all_unique_chars('world')) # True
Complexity: O(n) time, O(n) space
Time Complexity
Converting the string to a set takes O(n) time because it processes each character once.
Space Complexity
The set stores unique characters, which can be up to O(n) in the worst case if all characters are unique.
Which Approach is Fastest?
The set length comparison is simple and fast for most cases, but the loop method can be faster if duplicates appear early.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Set length comparison | O(n) | O(n) | Simple and fast for most strings |
| Loop with set and early exit | O(n) best case | O(n) | Strings with early duplicates |
| Sorting and neighbor check | O(n log n) | O(n) | When no extra memory is allowed |