Open In App

Count the number of unique characters in a given String

Last Updated : 19 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
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<Character> s = new HashSet<Character>();
 
    // 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




<script>
      // JavaScript code for the above approach
 
      // Program to count the number of
      // unique characters in a string
      function cntDistinct(str)
      {
       
          // Set to store unique characters
          // in the given string
          let s = new Set();
 
          // Loop to traverse the string
          for (let i = 0; i < str.length; i++) {
 
              // Insert current character
              // into the set
              s.add(str[i]);
          }
 
          // Return Answer
          return s.size;
      }
 
      // Driver Code
 
      let str = "geeksforgeeks";
      document.write(cntDistinct(str));
 
// This code is contributed by Potta Lokesh
  </script>


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<bits/stdc++.h>
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<Character, Integer> 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<Character, Integer> 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 <bits/stdc++.h>
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<n; i++)
    {
        let curr_pos = str[i].charCodeAt(0) - "a".charCodeAt(0);
         
        // setting the curr_pos using left shift
        // operator
        freq = freq | (1 << curr_pos);
         
        // already if we have seen that character we are
        // making it again1
    }
     
    // counting how many characters are there by counting
    // set bits in the freq
    let ans = 0;
    while(freq != 0){
        if((freq & 1) == 1) ans++;
        freq = freq >> 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 <bits/stdc++.h>
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[26] = {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[26]; // 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)



Similar Reads

Modify string by inserting characters such that every K-length substring consists of unique characters only
Given string S of size N consisting of K distinct characters and (N - K) '?'s, the task is to replace all '?' with existing characters from the string such that every substring of size K has consisted of unique characters only. If it is not possible to do so, then print "-1". Examples: Input: S = "????abcd", K = 4Output: abcdabcdExplanation:Replaci
6 min read
Count the number of unique characters in a string in Python
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
5 min read
Minimum deletions from string to reduce it to string with at most 2 unique characters
Given a string [Tex]S [/Tex]containing lowercase English alphabets. The task is to find the minimum number of characters needed to be removed so that the remaining string contains at most 2 unique characters. Note: The final string can have duplicate characters. The task is only to reduce the string with minimum deletions such that there can be a m
5 min read
Modify characters of a string by adding integer values of same-indexed characters from another given string
Given two strings S and N of the same length, consisting of alphabetical and numeric characters respectively, the task is to generate a new string obtained by adding the integer value of each character of string N with the ASCII value of the same indexed character of string S. Finally, print the resultant string.Note: If the sum exceeds 122, then s
6 min read
Create a string with unique characters from the given N substrings
Given an array arr[] containing N substrings consisting of lowercase English letters, the task is to return the minimum length string that contains all given parts as a substring. All characters in this new answer string should be distinct. If there are multiple strings with the following property present, you have to print the string with minimum
11 min read
Smallest string containing all unique characters from given array of strings
Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are used across all the strings of the given array. Inp
9 min read
Find two unique Palindrome Strings using given String characters
You are given a string S of two distinct characters as input, the task is to find two strings using characters of the given string, such that both strings are different from S and both should be a palindrome. Examples: Input: S = "xyyxxxx"Output: yxxxxxy, xxyxyxxExplanation: It can be verified that at least one of the output strings is different fr
16 min read
Find the longest substring with k unique characters in a given string
Given a string you need to print longest possible substring that has exactly M unique characters. If there is more than one substring of longest possible length, then print any one of them. Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max substring can be any one from {"aa" , "bb" , "cc"}. Input: Str = "aabbcc", k = 2Output: 4Explana
19 min read
Minimize number of unique characters in string
Given two strings A and B. Minimize the number of unique characters in string A by either swapping A[i] with B[i] or keeping it unchanged. The number of swaps can be greater than or equal to 0. Note that A[i] can be swapped only with same index element in B. Print the minimum number of unique characters. Constraints: 0 &lt; length of A ≤ 15. Exampl
11 min read
String with maximum number of unique characters
Given a list of strings Str, find the largest string among all. The largest string is the string with the largest number of unique characters. Example: Input: Str[] = {"AN KOW", "LO JO", "ZEW DO RO" }Output: "ZEW DO RO" Explanation: "ZEW DO RO" has maximum distinct letters. Input: Str[] = {"ROMEO", "EMINEM", "RADO"}Output: "ROMEO" Explanation: In c
16 min read