Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python program to check if a string contains all unique characters

  • Difficulty Level : Easy
  • Last Updated : 22 Mar, 2021

To implement an algorithm to determine if a string contains all unique characters. 

Input : s = “abcd” 
Output: True 
“abcd” doesn’t contain any duplicates. Hence the output is True.

Input : s = “abbd” 
Output: False 
“abbd” contains duplicates. Hence the output is False.

One solution is to create an array of boolean values, where the flag at the index i indicates whether character i in the alphabet is contained in the string. The second time you see this character you can immediately return false. 
You can also return false if the string length exceeds the number of unique characters in the alphabet.  


def isUniqueChars(st):
    # String length cannot be more than
    # 256.
    if len(st) > 256:
        return False
    # Initialize occurrences of all characters
    char_set = [False] * 128
    # For every character, check if it exists
    # in char_set
    for i in range(0, len(st)):
        # Find ASCII value and check if it
        # exists in set.
        val = ord(st[i])
        if char_set[val]:
            return False
        char_set[val] = True
    return True
# driver code
st = "abcd"



Method #2:Using Built-in Python Functions:

  • Count the frequencies of characters using Counter() function
  • If the keys in frequency dictionary(gives the count of distinct characters) is equal to length of string then print True else False

Below is the implementation:


from collections import Counter
def isUniqueChars(string):
    # Counting frequency
    freq = Counter(string)
    if(len(freq) == len(string)):
        return True
        return False
# driver code
st = "abcd"
# This code is contributed by vikkycirus



Time Complexity:O(N)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!