 GeeksforGeeks App
Open App Browser
Continue

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

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:

## C++

 `// C++ program of the above approach``#include ``using` `namespace` `std;` `// Program to count the number of``// unique characters in a string``int` `cntDistinct(string str)``{``    ``// Set to store unique characters``    ``// in the given string``    ``unordered_set<``char``> s;` `    ``// Loop to traverse the string``    ``for` `(``int` `i = 0; i < str.size(); i++) {` `        ``// Insert current character``        ``// into the set``        ``s.insert(str[i]);``    ``}` `    ``// Return Answer``    ``return` `s.size();``}` `// Driver Code``int` `main()``{``    ``string str = ``"geeksforgeeks"``;``    ``cout << cntDistinct(str);` `    ``return` `0;``}`

## Java

 `// Java program of the above approach``import` `java.util.*;` `class` `GFG{` `// Program to count the number of``// unique characters in a string``static` `int` `cntDistinct(String str)``{``    ` `    ``// Set to store unique characters``    ``// in the given string``    ``HashSet s = ``new` `HashSet();` `    ``// Loop to traverse the string``    ``for``(``int` `i = ``0``; i < str.length(); i++)``    ``{``        ` `        ``// Insert current character``        ``// into the set``        ``s.add(str.charAt(i));``    ``}` `    ``// Return Answer``    ``return` `s.size();``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``String str = ``"geeksforgeeks"``;``    ``System.out.print(cntDistinct(str));``}``}` `// This code is contributed by sanjoy_62`

## Python3

 `# Python 3 program of the above approach` `# Program to count the number of``# unique characters in a string``def` `cntDistinct(st):` `    ``# Set to store unique characters``    ``# in the given string``    ``s ``=` `set``([])` `    ``# Loop to traverse the string``    ``for` `i ``in` `range``(``len``(st)):` `        ``# Insert current character``        ``# into the set``        ``s.add(st[i])` `    ``# Return Answer``    ``return` `len``(s)` `# Driver Code``if` `__name__ ``=``=` `"__main__"``:` `    ``st ``=` `"geeksforgeeks"``    ``print``(cntDistinct(st))` `    ``# This code is contributed by ukasp.`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG``{` `// Program to count the number of``// unique characters in a string``static` `int` `cntDistinct(``string` `str)``{``    ` `    ``// Set to store unique characters``    ``// in the given string``    ``HashSet<``char``> s = ``new` `HashSet<``char``>();` `    ``// Loop to traverse the string``    ``for``(``int` `i = 0; i < str.Length; i++)``    ``{``        ` `        ``// Insert current character``        ``// into the set``        ``s.Add(str[i]);``    ``}` `    ``// Return Answer``    ``return` `s.Count;``}` `// Driver Code``public` `static` `void` `Main()``{``    ``string` `str = ``"geeksforgeeks"``;``    ``Console.Write(cntDistinct(str));``}``}` `// This code is contributed by Samim Hossain Mondal.`

## Javascript

 ``

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

## C++

 `#include``using` `namespace` `std;` `int` `cntDistinct(string str){``    ``map<``char``, ``int``> count;``    ``for``(``int` `i = 0; i < str.size(); i++){``        ``count[str[i]]++;``    ``}``    ``return` `count.size();``}``signed` `main(){``    ``string str = ``"geeksforgeeks"``;``    ``int` `ans = cntDistinct(str);``    ``cout << ans;``    ``cout << endl;``    ``return` `0;``}`

## Java

 `// Implementation in Java language``import` `java.util.*;` `class` `GFG``{` `  ``static` `void` `countFreq(String arr, ``int` `n)``  ``{``    ``Map mp = ``new` `HashMap<>();` `    ``// Traverse through array elements and``    ``// count frequencies``    ``for` `(``int` `i = ``0``; i < n; i++)``    ``{``      ``if` `(mp.containsKey(arr.charAt(i)))``      ``{``        ``mp.put(arr.charAt(i), mp.get(arr.charAt(i)) + ``1``);``      ``}``      ``else``      ``{``        ``mp.put(arr.charAt(i), ``1``);``      ``}``    ``}``    ``int` `count = ``0``;``    ``// Traverse through map and print frequencies``    ``for` `(Map.Entry entry : mp.entrySet())``    ``{``      ``count += ``1``;``    ``}``    ``System.out.println(count);` `  ``}` `  ``// Driver code``  ``public` `static` `void` `main(String args[])``  ``{``    ``String arr = ``"geeksforgeeks"``;``    ``int` `n = arr.length();``    ``countFreq(arr, n);``  ``}``}` `// This code contributed by Prince Kumar`

## Python3

 `def` `cntDistinct(``str``):``    ``# created a empty dictionary over here``    ``count ``=` `{}``    ``for` `i ``in` `range``(``len``(``str``)):``        ``# we are checking that if element already exist``        ``# we will be incrementing the count of element by 1``        ``if` `str``[i] ``in` `count:``            ``count[``str``[i]] ``+``=` `1``        ``# if exist in count then insert that element``        ``# and initialize its count by 1``        ``else``:``            ``count[``str``[i]] ``=` `1``    ``return` `len``(count)` `string ``=` `"geeksforgeeks"``ans ``=` `cntDistinct(string)``print``(ans)`

## C#

 `// Implementation in C# language``using` `System;``using` `System.Collections.Generic;` `public` `class` `GFG {``  ``static` `int` `cntDistinct(``string` `str)``  ``{``    ``Dictionary<``char``, ``int``> count``      ``= ``new` `Dictionary<``char``, ``int``>();``    ``for` `(``int` `i = 0; i < str.Length; i++) {` `      ``// we are checking that if element already exist``      ``// we will be incrementing the count of element by 1``      ``if` `(count.ContainsKey(str[i]))``        ``count[str[i]]++;` `      ``// if exist in count then insert that element``      ``// and initialize its count by 1``      ``else``        ``count[str[i]] = 1;``    ``}``    ``return` `count.Count;``  ``}` `  ``// Driver Code``  ``static` `public` `void` `Main(``string``[] args)``  ``{``    ``string` `str = ``"geeksforgeeks"``;``    ``int` `ans = cntDistinct(str);``    ``Console.WriteLine(ans);``  ``}``}` `// This Code is Contributed by Prasad Kandekar(prasad264)`

## Javascript

 `// JavaScript Code for the above approach``function` `cntDistinct(str){``    ``let count = ``new` `Map();``    ``for``(let i = 0; i < str.length; i++){``        ``if``(count.has(str[i])){``            ``count.set(str[i], count.get(str[i])+1);``        ``}``        ``else``{``            ``count.set(str[i],1);``        ``}``    ``}``    ``return` `count.size;``}` `// driver Code``    ``let str = ``"geeksforgeeks"``;``    ``let ans = cntDistinct(str);``    ``console.log(ans);`` ` ` ``// This code is contributed by poojaagarwal2.`

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.

## C++

 `#include ``using` `namespace` `std;` `int` `countDistinct(string str)``{``    ``int` `freq = 0;``    ``// If the position of zeroth bit is set which means``    ``// we have seen letter 'a' If the position of 25th``    ``// bit is set which means we have seen letter 'z'``    ``int` `n = str.size();``    ``for` `(``int` `i = 0; i < n; i++) {``        ``int` `curr_pos = str[i] - ``'a'``;``        ``// setting the curr_pos using left shift``        ``// operator``        ``freq = freq | (1 << curr_pos);``        ``// Already if we have seen that character we are``        ``// making it again 1``    ``}``    ``// Couting how many characters are there by counting``    ``// set bits in the freq``    ``int` `ans = 0;``    ``while` `(freq != 0) {``        ``if` `((freq & 1) == 1)``            ``ans++;``        ``freq = freq >> 1;``    ``}``    ``return` `ans;``}``//Driver code``int` `main(){``    ``string str = ``"geeksforgeeks"``;``    ``int` `ans = countDistinct(str);``    ``cout << ans << endl;``}``//This code is contributed by Vishal Dhaygude`

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;` `class` `GFG {``    ``public` `static` `int` `countDistinct(String str)``    ``{``        ``int` `freq = ``0``;``        ``// If the position of zeroth bit is set which means``        ``// we have seen letter 'a' If the position of 25th``        ``// bit is set which means we have seen letter 'z'``        ``int` `n = str.length();``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``int` `curr_pos = str.charAt(i) - ``'a'``;``            ``// setting the curr_pos using left shift``            ``// operator``            ``freq = freq | (``1` `<< curr_pos);``            ``// Already if we have seen that character we are``            ``// making it again 1``        ``}``        ``// Couting how many characters are there by counting``        ``// set bits in the freq``        ``int` `ans = ``0``;``        ``while` `(freq != ``0``) {``            ``if` `((freq & ``1``) == ``1``)``                ``ans++;``            ``freq = freq >> ``1``;``        ``}``        ``return` `ans;``    ``}``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String str = ``"geeksforgeeks"``;``        ``int` `ans = countDistinct(str);``        ``System.out.println(ans);``    ``}``}`

## Python

 `def` `countDistinct(s):``    ``freq ``=` `0``    ``# If the position of zeroth bit is set which means``    ``# we have seen letter 'a' If the position of 25th``    ``# bit is set which means we have seen letter 'z'``    ``n ``=` `len``(s)``    ``for` `i ``in` `range``(n):``        ``curr_pos ``=` `ord``(s[i]) ``-` `ord``(``'a'``)``        ``# setting the curr_pos using left shift``        ``# operator``        ``freq ``=` `freq | (``1` `<< curr_pos)``        ``# Already if we have seen that character we are``        ``# making it again 1``    ``# Couting how many characters are there by counting``    ``# set bits in the freq``    ``ans ``=` `0``    ``while` `freq !``=` `0``:``        ``if` `freq & ``1` `=``=` `1``:``            ``ans ``+``=` `1``        ``freq ``=` `freq >> ``1``    ``return` `ans``s ``=` `"geeksforgeeks"``ans ``=` `countDistinct(s)``print``(ans)`

## C#

 `// C# code for the above approach``using` `System;` `class` `GFG {``  ``static` `int` `CountDistinct(``string` `str) {``    ``int` `freq = 0;` `    ``// If the position of zeroth bit is set which means``    ``// we have seen letter 'a' If the position of 25th``    ``// bit is set which means we have seen letter 'z'``    ``int` `n = str.Length;``    ``for` `(``int` `i = 0; i < n; i++) {``      ``int` `curr_pos = str[i] - ``'a'``;` `      ``// setting the curr_pos using left shift``      ``// operator``      ``freq = freq | (1 << curr_pos);` `      ``// Already if we have seen that character we are``      ``// making it again 1``    ``}` `    ``// Couting how many characters are there by counting``    ``// set bits in the freq``    ``int` `ans = 0;``    ``while` `(freq != 0) {``      ``if` `((freq & 1) == 1)``        ``ans++;``      ``freq = freq >> 1;``    ``}``    ``return` `ans;``  ``}` `  ``public` `static` `void` `Main(``string``[] args) {``    ``string` `str = ``"geeksforgeeks"``;``    ``int` `ans = CountDistinct(str);``    ``Console.WriteLine(ans);``  ``}``}` `// this code is contributed by bhardwajji`

## Javascript

 `// JavaScript program for the above approach``function` `countDistinct(str){``    ``let freq = 0;``    ` `    ``// If the position of zeroth bit is set which means``    ``// we have seen letter 'a' If the position of 25th``    ``// bit is set which means we have seen letter 'z'``    ``let n = str.length;``    ``for``(let i = 0; i> 1;``    ``}``    ``return` `ans;``}` `// driver function to check above function``let str = ``"geeksforgeeks"``;``let ans = countDistinct(str);``console.log(ans);` `// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGAWRAL2852002)`

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:

## C++

 `// C++ program of above approach``#include ``using` `namespace` `std;` `// Function to count distinct characters``int` `countDistinct(string s)``{``    ``transform(s.begin(), s.end(), s.begin(), ::``tolower``); ``// convert the string to lowercase``    ``int` `n = s.length(); ``// size of string``    ``int` `a = {0}; ``// an array of size 26, initialize with 0` `    ``// iterate over the string s``    ``for` `(``int` `i = 0; i < n; i++) {``        ``int` `index = s[i] - ``'a'``; ``// calculate index by (s[i] - 'a') in ASCII value``        ``a[index] = 1; ``// Set the value at index to 1``    ``}` `    ``int` `count = 0; ``// Take a counter with 0``    ` `    ``for` `(``int` `i = 0; i < 26; i++) { ``// Loop to 26``        ``// count no. of index having value 1``        ``if` `(a[i] == 1) {``            ``count += 1;``        ``}``       ``}``       ``return` `count;``}` `// Driver code``int` `main() {``    ``string s = ``"geeksforgeeks"``; ``// string taken``    ``cout << countDistinct(s) << endl; ``// Print answer``    ``return` `0;``}`

## Java

 `import` `java.util.*;` `public` `class` `Main {``    ``// Function to count distinct characters``    ``public` `static` `int` `countDistinct(String s) {``        ``s = s.toLowerCase(); ``// convert the string to lowercase``        ``int` `n = s.length(); ``// size of string``        ``int``[] a = ``new` `int``[``26``]; ``// an array of size 26, initialize with 0` `        ``// iterate over the string s``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``int` `index = s.charAt(i) - ``'a'``; ``// calculate index by (s[i] - 'a') in ASCII value``            ``a[index] = ``1``; ``// Set the value at index to 1``        ``}` `        ``int` `count = ``0``; ``// Take a counter with 0``        ``for` `(``int` `i = ``0``; i < ``26``; i++) { ``// Loop to 26``            ``// count no. of index having value 1``            ``if` `(a[i] == ``1``) {``                ``count += ``1``;``            ``}``        ``}``        ``return` `count;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args) {``        ``String s = ``"geeksforgeeks"``; ``// string taken``        ``System.out.println(countDistinct(s)); ``// Print answer``    ``}``}`

## Python3

 `# Function to count distinct characters``def` `countDistinct(s):``    ``s ``=` `s.lower() ``# convert the string to lowercase``    ``n ``=` `len``(s) ``# size of string``    ``a ``=` `[``0``] ``*` `26` `# an array of size 26, initialize with 0` `    ``# iterate over the string s``    ``for` `i ``in` `range``(n):``        ``index ``=` `ord``(s[i]) ``-` `ord``(``'a'``) ``# calculate index by (s[i] - 'a') in ASCII value``        ``a[index] ``=` `1` `# Set the value at index to 1` `    ``count ``=` `0` `# Take a counter with 0``    ``for` `i ``in` `range``(``26``): ``# Loop to 26``        ``# count no. of index having value 1``        ``if` `a[i] ``=``=` `1``:``            ``count ``+``=` `1``    ``return` `count` `# Driver code``s ``=` `"geeksforgeeks"` `# string taken``print``(countDistinct(s)) ``# Print answer`

## C#

 `using` `System;` `public` `class` `GFG``{``    ``// Function to count distinct characters``    ``public` `static` `int` `CountDistinct(``string` `s)``    ``{``        ``s = s.ToLower(); ``// convert the string to lowercase``        ``int` `n = s.Length; ``// size of string``        ``int``[] a = ``new` `int``; ``// an array of size 26, initialize with 0` `        ``// iterate over the string s``        ``for` `(``int` `i = 0; i < n; i++)``        ``{``            ``int` `index = s[i] - ``'a'``; ``// calculate index by (s[i] - 'a') in ASCII value``            ``a[index] = 1; ``// Set the value at index to 1``        ``}` `        ``int` `count = 0; ``// Take a counter with 0``        ``for` `(``int` `i = 0; i < 26; i++) ``// Loop to 26``        ``{``            ``// count no. of index having value 1``            ``if` `(a[i] == 1)``            ``{``                ``count += 1;``            ``}``        ``}``        ``return` `count;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``string` `s = ``"geeksforgeeks"``; ``// string taken``        ``Console.WriteLine(CountDistinct(s)); ``// Print answer``    ``}``}`

## Javascript

 `// JavaScript program of above approach` `// Function to count distinct characters``function` `countDistinct(s) {``    ``s = s.toLowerCase(); ``// convert the string to lowercase``    ``let n = s.length; ``// size of string``    ``let a = ``new` `Array(26).fill(0); ``// an array of size 26, initialize with 0``    ` `    ``// iterate over the string s``    ``for` `(let i = 0; i < n; i++) {``        ``let index = s.charCodeAt(i) - ``'a'``.charCodeAt(0); ``// calculate index by (s[i] - 'a') in ASCII value``        ``a[index] = 1; ``// Set the value at index to 1``    ``}``    ` `    ``let count = 0; ``// Take a counter with 0``    ` `    ``for` `(let i = 0; i < 26; i++) { ``// Loop to 26``        ``// count no. of index having value 1``        ``if` `(a[i] == 1) {``            ``count += 1;``        ``}``    ``}``    ``return` `count;``}` `// Driver code``let s = ``"geeksforgeeks"``; ``// string taken``console.log(countDistinct(s)); ``// Print answer`

Output

`7`

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

My Personal Notes arrow_drop_up