VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-the-number-of-unique-characters-in-a-given-string/

⇱ Count the number of unique characters in a given String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count the number of unique characters in a given String

Last Updated : 23 Jul, 2025

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: 7
Explanation: The given string “geeksforgeeks” contains 7 unique characters {‘g’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’}.

Input: str = “madam”
Output: 3

Approach: The given problem can be solved using the set data structure. The idea is to initialize an unordered set that stores all the distinct characters of the given string. The size of the set after the string is traversed is the required answer.

Below is the implementation of the above approach:


Output
7

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

Another approach using map/dictionary data structure. 

# Algorithm
Step 1: First we create key value data pair structure
Step 2: After creating data structure Run a conditional for loop for storing the elements in the created data structure.
Step 3: Finally print the size of the data Structure


Output
7

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

Approach:  The above two approaches uses extra space. In this approach we are going to use an integer to store whether we have seen the character or not. It is similar to storing the frequency of array. But we don't need to store how many times  we have seen that particular character. since we are using it only for English lower case letters. only 26 bits we are going to use.


Output
7

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

Note: The above Code not works if we have all characters. To make it versatile we have to use long Double data type. where we can incorporate all frequency of every character.

Approach: Simple approach in which counting number of alphabets present in string using array.

1. Take a string s and convert it into lowercase if not.
2. Create an array arr of size 26 with 0.
3. Loop the the string s.
4. Update the value of array arr[ s[i] -' a' ] or a[ s[i] - 97] to 1.
5. Take a counter count = 0;
6. Take loop to 26 and check if arr[i] is equal to 1 then increment the value of count by 1.
7. Print the value of count.

Below is the implementation of the above approach:


Output
7

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

Comment