Count the number of unique characters in a given String
Last Updated :
19 Apr, 2023
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>
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.
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)
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
Time Complexity: O(N)
Auxiliary Space: O(1)
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 du
2 min read
Count the Number of matching characters in a pair of strings Given a pair of non-empty strings str1 and str2, the task is to count the number of matching characters in these strings. Consider the single count for the character which have duplicates in the strings.Examples: Input: str1 = "abcdef", str2 = "defghia" Output: 4 Matching characters are: a, d, e, fI
7 min read
Count Occurrences of a Given Character in a String Given a string S and a character 'c', the task is to count the occurrence of the given character in the string.Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str.Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times in
6 min read
Number of sub-strings that contain the given character exactly k times Given the string str, a character c, and an integer k > 0. The task is to find the number of sub-strings that contain the character c exactly k times.Examples: Input: str = "abada", c = 'a', K = 2 Output: 4 All possible sub-strings are "aba", "abad", "bada" and "ada". Input: str = "55555", c = '5
10 min read
Count of substrings which contains a given character K times Given a string consisting of numerical alphabets, a character C and an integer K, the task is to find the number of possible substrings which contains the character C exactly K times. Examples: Input : str = "212", c = '2', k = 1 Output : 4 Possible substrings are {"2", "21", "12", "2"} that contain
9 min read
Count number of substrings having at least K distinct characters Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters.Examples:Input: S = "abcca", K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are:"abc": Count of distinc
7 min read
Python program to check if a string contains all unique characters 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 cre
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
Count of Substrings that can be formed without using the given list of Characters Given a string str and a list of characters L, the task is to count the total numbers of substrings of the string str without using characters given in the list L. Examples: Input: str = "abcd", L[] = {'a', 'b', 't', 'q'} Output: 3 Explanation: On ignoring the characters 'a' and 'b' from the given s
7 min read
Count of sub-strings that do not consist of the given character Given a string str and a character c. The task is to find the number of sub-strings that do not consist of the character c. Examples: Input: str = "baa", c = 'b' Output: 3 The sub-strings are "a", "a" and "aa" Input: str = "ababaa", C = 'b' Output: 5 Approach: Initially take a counter that counts th
12 min read