Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Count the number of Unique Characters in a String in Python
Next article icon

Python program to check if a string contains all unique characters

Last Updated : 28 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Examples: 

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.  

Implementation:

Python




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"
print(isUniqueChars(st))
 
 
Output
True

Complexity Analysis:

  • Time Complexity: O(N), where N is the length of the string.
  • Auxiliary Space: O(1), no extra space required so it is a constant.

Method #2:Using Built-in Python Functions:

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

Implementation:

Python3




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

Complexity Analysis:

  • Time Complexity: O(N), where N is the length of the string.
  • Auxiliary Space: O(26), in total there are 26 letters in alphabet and no extra space required so it is a constant.

Method #3 : Using list() and set() methods

Python3




st = "abcbd"
x=list(set(st))
y=list(st)
x.sort()
y.sort()
if(x==y):
    print(True)
else:
    print(False)
 
 
Output
False

Time Complexity: O(logn)
Auxiliary Space: O(1)

Method #4: Using for loop and membership operators

Python3




st = "abcbd"
a=""
for i in st:
    if i not in a:
        a+=i
if(a==st):
    print(True)
else:
    print(False)
 
 
Output
False

Time Complexity: O(N)
Auxiliary Space: O(N)

Method #5 : Using Operator.countOf() function

Python3




import operator as op
 
 
def isUniqueChars(string):
 
    for i in string:
        if op.countOf(string, i) > 1:
            return False
    return True
 
 
# driver code
st = "abcd"
print(isUniqueChars(st))
 
 
Output
True

Complexity Analysis:

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1), no extra space required so it is a constant.

Method #6 : Using count() function

Python3




def isUniqueChars(string):
 
    for i in string:
        if string.count(i) > 1:
            return False
    return True
 
 
# driver code
st = "abcd"
print(isUniqueChars(st))
 
 
Output
True

Time Complexity: O(N)
Auxiliary Space: O(1)



Next Article
Count the number of Unique Characters in a String in Python

M

manogna tata
Improve
Article Tags :
  • Algorithms
  • DSA
  • Technical Scripter
  • Technical Scripter 2018
Practice Tags :
  • Algorithms

Similar Reads

  • Count the number of Unique Characters in a String in Python
    We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8. Using setSet in Python is an unordered collection of unique elements automatically removing d
    2 min read
  • Determine if a string has all Unique Characters
    Given a string, determine if the string has all unique characters. Examples : Input : abcd10jk Output : true Input : hutg9mnd!nk9 Output : false Approach 1 - Brute Force technique: Run 2 loops with variable i and j. Compare str[i] and str[j]. If they become equal at any point, return false. C/C++ Co
    15+ min read
  • Count the number of unique characters in a given String
    Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = “geeksforgeeks”Output: 7Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}. Inp
    14 min read
  • Python | Check if frequencies of all characters of a string are different
    Given a string S consisting only of lowercase letters, the task is to check if the frequency of all characters of the string is unique. Examples: Input : abaccc Output : Yes ‘a’ occurs two times, ‘b’ occurs once and ‘c’ occurs three times. Input : aabbc Output : No Frequency of both 'a' and 'b' are
    3 min read
  • Check if a string consists only of special characters
    Given string str of length N, the task is to check if the given string contains only special characters or not. If the string contains only special characters, then print “Yes”. Otherwise, print “No”. Examples: Input: str = “@#$&%!~”Output: YesExplanation: Given string contains only special char
    9 min read
  • Python | Check order of character in string using OrderedDict( )
    Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All
    3 min read
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Check if String Contains Substring in Python
    This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
    8 min read
  • Print all the duplicate characters in a string
    Given a string S, the task is to print all the duplicate characters with their occurrences in the given string. Example: Input: S = "geeksforgeeks"Output: e, count = 4 g, count = 2 k, count = 2 s, count = 2 Explanation: g occurs 2 times in the string, k occurs 2 times in the string, s occurs 2 times
    8 min read
  • Quick way to check if all the characters of a string are same
    Given a string, check if all the characters of the string are the same or not. Examples: Input : s = "geeks"Output : No Input : s = "gggg" Output : Yes Recommended PracticeCheck StringTry It! Simple Way To find whether a string has all the same characters. Traverse the whole string from index 1 and
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences