Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to check if a string contains all unique characters
In this article, we will learn different approaches to check if a string contains all unique characters. This is a common programming problem that tests our understanding of data structures and string manipulation.
Problem Statement
Given a string input, we need to determine whether all characters in the string are unique (no character appears more than once).
Using Boolean Array
We can create an array of boolean values to track which characters we have seen. If we encounter a character that we've already seen, we return False immediately.
Example
def isUniqueChars(st):
if len(st) > 256:
return False
# Initialize boolean array for ASCII characters
char_set = [False] * 128
for i in range(len(st)):
# Get ASCII value of character
val = ord(st[i])
# If character already seen, return False
if char_set[val]:
return False
# Mark character as seen
char_set[val] = True
return True
# Test with different strings
print("tutorialspoint:", isUniqueChars("tutorialspoint"))
print("python:", isUniqueChars("python"))
print("abc:", isUniqueChars("abc"))
tutorialspoint: False python: False abc: True
Using Python Set
A more Pythonic approach is to use a set data structure, which automatically handles uniqueness.
Example
def isUniqueCharsSet(st):
# Compare string length with set length
return len(st) == len(set(st))
# Test with different strings
print("tutorialspoint:", isUniqueCharsSet("tutorialspoint"))
print("python:", isUniqueCharsSet("python"))
print("abc:", isUniqueCharsSet("abc"))
print("hello:", isUniqueCharsSet("hello"))
tutorialspoint: False python: False abc: True hello: False
Using Dictionary for Character Counting
Another approach is to count character frequencies and check if any character appears more than once.
Example
def isUniqueCharsDict(st):
char_count = {}
for char in st:
if char in char_count:
return False
char_count[char] = 1
return True
# Test with different strings
print("tutorialspoint:", isUniqueCharsDict("tutorialspoint"))
print("python:", isUniqueCharsDict("python"))
print("world:", isUniqueCharsDict("world"))
tutorialspoint: False python: False world: True
Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Boolean Array | O(n) | O(1) fixed size | ASCII strings |
| Set | O(n) | O(n) | Clean, Pythonic code |
| Dictionary | O(n) | O(n) | When you need character counts |
Conclusion
The set-based approach is most Pythonic and readable. Use the boolean array method for performance-critical applications with ASCII strings. All methods have O(n) time complexity but differ in space usage and readability.
