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++
#include <bits/stdc++.h>
using namespace std;
int cntDistinct(string str)
{
unordered_set< char > s;
for ( int i = 0; i < str.size(); i++) {
s.insert(str[i]);
}
return s.size();
}
int main()
{
string str = "geeksforgeeks" ;
cout << cntDistinct(str);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int cntDistinct(String str)
{
HashSet<Character> s = new HashSet<Character>();
for ( int i = 0 ; i < str.length(); i++)
{
s.add(str.charAt(i));
}
return s.size();
}
public static void main(String args[])
{
String str = "geeksforgeeks" ;
System.out.print(cntDistinct(str));
}
}
|
Python3
def cntDistinct(st):
s = set ([])
for i in range ( len (st)):
s.add(st[i])
return len (s)
if __name__ = = "__main__" :
st = "geeksforgeeks"
print (cntDistinct(st))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int cntDistinct( string str)
{
HashSet< char > s = new HashSet< char >();
for ( int i = 0; i < str.Length; i++)
{
s.Add(str[i]);
}
return s.Count;
}
public static void Main()
{
string str = "geeksforgeeks" ;
Console.Write(cntDistinct(str));
}
}
|
Javascript
<script>
function cntDistinct(str)
{
let s = new Set();
for (let i = 0; i < str.length; i++) {
s.add(str[i]);
}
return s.size;
}
let str = "geeksforgeeks" ;
document.write(cntDistinct(str));
</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
import java.util.*;
class GFG
{
static void countFreq(String arr, int n)
{
Map<Character, Integer> mp = new HashMap<>();
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 ;
for (Map.Entry<Character, Integer> entry : mp.entrySet())
{
count += 1 ;
}
System.out.println(count);
}
public static void main(String args[])
{
String arr = "geeksforgeeks" ;
int n = arr.length();
countFreq(arr, n);
}
}
|
Python3
def cntDistinct( str ):
count = {}
for i in range ( len ( str )):
if str [i] in count:
count[ str [i]] + = 1
else :
count[ str [i]] = 1
return len (count)
string = "geeksforgeeks"
ans = cntDistinct(string)
print (ans)
|
C#
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++) {
if (count.ContainsKey(str[i]))
count[str[i]]++;
else
count[str[i]] = 1;
}
return count.Count;
}
static public void Main( string [] args)
{
string str = "geeksforgeeks" ;
int ans = cntDistinct(str);
Console.WriteLine(ans);
}
}
|
Javascript
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;
}
let str = "geeksforgeeks" ;
let ans = cntDistinct(str);
console.log(ans);
|
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;
int n = str.size();
for ( int i = 0; i < n; i++) {
int curr_pos = str[i] - 'a' ;
freq = freq | (1 << curr_pos);
}
int ans = 0;
while (freq != 0) {
if ((freq & 1) == 1)
ans++;
freq = freq >> 1;
}
return ans;
}
int main(){
string str = "geeksforgeeks" ;
int ans = countDistinct(str);
cout << ans << endl;
}
|
Java
import java.io.*;
class GFG {
public static int countDistinct(String str)
{
int freq = 0 ;
int n = str.length();
for ( int i = 0 ; i < n; i++) {
int curr_pos = str.charAt(i) - 'a' ;
freq = freq | ( 1 << curr_pos);
}
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
n = len (s)
for i in range (n):
curr_pos = ord (s[i]) - ord ( 'a' )
freq = freq | ( 1 << curr_pos)
ans = 0
while freq ! = 0 :
if freq & 1 = = 1 :
ans + = 1
freq = freq >> 1
return ans
s = "geeksforgeeks"
ans = countDistinct(s)
print (ans)
|
C#
using System;
class GFG {
static int CountDistinct( string str) {
int freq = 0;
int n = str.Length;
for ( int i = 0; i < n; i++) {
int curr_pos = str[i] - 'a' ;
freq = freq | (1 << curr_pos);
}
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);
}
}
|
Javascript
function countDistinct(str){
let freq = 0;
let n = str.length;
for (let i = 0; i<n; i++)
{
let curr_pos = str[i].charCodeAt(0) - "a" .charCodeAt(0);
freq = freq | (1 << curr_pos);
}
let ans = 0;
while (freq != 0){
if ((freq & 1) == 1) ans++;
freq = freq >> 1;
}
return ans;
}
let str = "geeksforgeeks" ;
let ans = countDistinct(str);
console.log(ans);
|
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++
#include <bits/stdc++.h>
using namespace std;
int countDistinct(string s)
{
transform(s.begin(), s.end(), s.begin(), :: tolower );
int n = s.length();
int a[26] = {0};
for ( int i = 0; i < n; i++) {
int index = s[i] - 'a' ;
a[index] = 1;
}
int count = 0;
for ( int i = 0; i < 26; i++) {
if (a[i] == 1) {
count += 1;
}
}
return count;
}
int main() {
string s = "geeksforgeeks" ;
cout << countDistinct(s) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int countDistinct(String s) {
s = s.toLowerCase();
int n = s.length();
int [] a = new int [ 26 ];
for ( int i = 0 ; i < n; i++) {
int index = s.charAt(i) - 'a' ;
a[index] = 1 ;
}
int count = 0 ;
for ( int i = 0 ; i < 26 ; i++) {
if (a[i] == 1 ) {
count += 1 ;
}
}
return count;
}
public static void main(String[] args) {
String s = "geeksforgeeks" ;
System.out.println(countDistinct(s));
}
}
|
Python3
def countDistinct(s):
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
return count
s = "geeksforgeeks"
print (countDistinct(s))
|
C#
using System;
public class GFG
{
public static int CountDistinct( string s)
{
s = s.ToLower();
int n = s.Length;
int [] a = new int [26];
for ( int i = 0; i < n; i++)
{
int index = s[i] - 'a' ;
a[index] = 1;
}
int count = 0;
for ( int i = 0; i < 26; i++)
{
if (a[i] == 1)
{
count += 1;
}
}
return count;
}
public static void Main( string [] args)
{
string s = "geeksforgeeks" ;
Console.WriteLine(CountDistinct(s));
}
}
|
Javascript
function countDistinct(s) {
s = s.toLowerCase();
let n = s.length;
let a = new Array(26).fill(0);
for (let i = 0; i < n; i++) {
let index = s.charCodeAt(i) - 'a' .charCodeAt(0);
a[index] = 1;
}
let count = 0;
for (let i = 0; i < 26; i++) {
if (a[i] == 1) {
count += 1;
}
}
return count;
}
let s = "geeksforgeeks" ;
console.log(countDistinct(s));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...