0
0
PythonProgramBeginner · 2 min read

Python Program to Check if String Has All Unique Characters

You can check if a string has all unique characters in Python by using len(set(string)) == len(string), which compares the length of the string to the length of the set of its characters.
📋

Examples

Inputhello
OutputFalse
Inputworld
OutputTrue
Input
OutputTrue
🧠

How to Think About It

To check if all characters in a string are unique, think about comparing the number of characters in the string to the number of unique characters. If both counts are the same, then all characters are unique; otherwise, some characters repeat.
📐

Algorithm

1
Get the input string.
2
Convert the string into a set to keep only unique characters.
3
Compare the length of the set with the length of the original string.
4
If both lengths are equal, return True; else, return False.
💻

Code

python
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
Output
False True True
🔍

Dry Run

Let's trace the string 'hello' through the code

1

Input string

s = 'hello'

2

Convert to set

set(s) = {'h', 'e', 'l', 'o'}

3

Compare lengths

len(set(s)) = 4, len(s) = 5

4

Return result

4 == 5 is False, so return False

IterationSet ContentSet LengthString LengthResult
1{'h', 'e', 'l', 'o'}45False
💡

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

Using a loop and a set to check duplicates
python
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
This method stops early when a duplicate is found, which can be faster for long strings with duplicates.
Sorting the string and checking neighbors
python
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
This method uses sorting and compares adjacent characters; it uses more time due to sorting but no extra set memory.

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.

ApproachTimeSpaceBest For
Set length comparisonO(n)O(n)Simple and fast for most strings
Loop with set and early exitO(n) best caseO(n)Strings with early duplicates
Sorting and neighbor checkO(n log n)O(n)When no extra memory is allowed
💡
Use a set to quickly identify unique characters because sets automatically remove duplicates.
⚠️
Beginners often forget that strings can have repeated characters and assume all strings are unique by default.