Count the number of unique characters in a string in Python
Last Updated :
23 Mar, 2023
Given a string S consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string.
Examples:
Input: S = "geeksforgeeks"
Output: 7
Explanation: The given string "geeksforgeeks" contains 6 unique characters {'g', 'e', 'k', 's', 'f', 'o', 'r'}.
Input: S = "madam"
Output: 3
Approach: The idea to solve the given problem is to initialize a Set() in python to store all distinct characters of the given string and then, print the size of the set as the required answer.
Below is the implementation of the above approach:
Python3
def countDis( str ):
s = set ( str )
return len (s)
if __name__ = = "__main__" :
S = "geeksforgeeks"
print (countDis(S))
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N) // An extra variable store all the characters of the string and in worst case all characters will be unique hence algorithm takes up linear space
Method 2: Using Counter function:
Count the frequencies of all elements using Counter function and number of keys of this frequency dictionary gives the result.
Below is the implementation:
Python3
from collections import Counter
def countDis( str ):
freq = Counter( str )
return len (freq)
if __name__ = = "__main__" :
S = "geeksforgeeks"
print (countDis(S))
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N) an extra variable stores all the frequencies of the string hence algorithm takes up linear space
Method 3: Without using any builtin method
- Input a string and initialize another empty string
- Iterate a for loop on given string and check if each character of given string is present in empty string
- If not present append the characters to empty string.
- Now the empty string consists of only unique characters, use len() method to display the length.
Python3
S = "geeksforgeeks"
a = ""
for i in S:
if i not in a:
a + = i
print ( len (a))
|
Time Complexity : O(N^2) due to not in function of Python
Auxiliary Space: O(N) due to creating an extra string.
Method #4 : Using operator.countOf()
Python3
import operator as op
S = "geeksforgeeks"
a = ""
for i in S:
if op.countOf( list (a), i) = = 0 :
a + = i
print ( len (a))
|
Time Complexity:O(N)
Auxiliary Space: O(N)
Method 5: Using a hash table or dictionary
Use a hash table or dictionary to keep track of the frequency of each character in the given string. Iterate over the characters of the string and increment the frequency count of each character in the dictionary. Finally, return the number of keys in the dictionary as the count of distinct characters in the string.
Python3
def countDis( str ):
freq = {}
for char in str :
freq[char] = freq.get(char, 0 ) + 1
return len (freq)
if __name__ = = "__main__" :
S = "geeksforgeeks"
print (countDis(S))
|
Time Complexity: O(n)
Auxiliary Space: O(k), where k is the number of distinct characters in the input string.
Method 6: Using numpy:
Algorithm:
Convert the input string to a list.
Use the np.unique function to get a list of unique elements in the input list.
Get the length of the resulting list.
Python3
import numpy as np
def countDis( str ):
return len (np.unique( list ( str )))
S = "geeksforgeeks"
print (countDis(S))
|
Output:
7
Time complexity: O(nlogn)
Converting the input string to a list takes O(n) time.
np.unique function internally sorts the input list which takes O(nlogn) time complexity.
Getting the length of the resulting list takes O(1) time.
Auxiliary Space: O(n)
Converting the input string to a list takes O(n) space complexity.
The np.unique function creates a new list to store unique elements which takes O(n) space complexity.
Getting the length of the resulting list takes O(1) space.
Method 7: Using array.
Simple approach in which counting number of alphabets present in string using array.
1. Take a string s and convert it into lowercase.
2. Create an array a of size 26 with 0.
3. Loop through the string s
4. Inside the loop, set the value of a[ord(s[i]) – ord(‘a’)] to 1.
5. Take a counter count = 0;
6. Loop to range 26 and check if a[i] is equal to 1.
7. If a[i] is equal to 1, increment count by 1.
8. Print the value of count.
Python3
s = "geeksforgeeks"
s = s.lower()
n = len (s)
a = [ 0 ] * 26
for i in range (n):
index = ord (s[i]) - ord ( 'a' )
a[index] = 1
count = 0
for i in range ( 26 ):
if a[i] = = 1 :
count + = 1
print (count)
|
Time complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...