Algorithm: Let input string be “geeksforgeeks”
- Construct character count array from the input string.
- count[‘e’] = 4
- count[‘g’] = 2
- count[‘k’] = 2
- ……
- Print all the indexes from the constructed array which have values greater than 1.
Implementation:
C++14
#include <iostream>
using namespace std;
# define NO_OF_CHARS 256
class gfg
{
public :
void fillCharCounts( char *str, int *count)
{
int i;
for (i = 0; *(str + i); i++)
count[*(str + i)]++;
}
void printDups( char *str)
{
int *count = ( int *) calloc (NO_OF_CHARS,
sizeof ( int ));
fillCharCounts(str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1)
printf ( "%c, count = %d \n" , i, count[i]);
free (count);
}
};
int main()
{
gfg g ;
char str[] = "test string" ;
g.printDups(str);
return 0;
}
|
C
# include <stdio.h>
# include <stdlib.h>
# define NO_OF_CHARS 256
void fillCharCounts( char *str, int *count)
{
int i;
for (i = 0; *(str+i); i++)
count[*(str+i)]++;
}
void printDups( char *str)
{
int *count = ( int *) calloc (NO_OF_CHARS,
sizeof ( int ));
fillCharCounts(str, count);
int i;
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1)
printf ( "%c, count = %d \n" , i, count[i]);
free (count);
}
int main()
{
char str[] = "test string" ;
printDups(str);
getchar ();
return 0;
}
|
Java
public class GFG {
static final int NO_OF_CHARS = 256 ;
static void fillCharCounts(String str,
int [] count)
{
for ( int i = 0 ; i < str.length(); i++)
count[str.charAt(i)]++;
}
static void printDups(String str)
{
int count[] = new int [NO_OF_CHARS];
fillCharCounts(str, count);
for ( int i = 0 ; i < NO_OF_CHARS; i++)
if (count[i] > 1 )
System.out.println(( char )(i) +
", count = " + count[i]);
}
public static void main(String[] args)
{
String str = "test string" ;
printDups(str);
}
}
|
Python
NO_OF_CHARS = 256
def fillCharCounts(string, count):
for i in string:
count[ ord (i)] + = 1
return count
def printDups(string):
count = [ 0 ] * NO_OF_CHARS
count = fillCharCounts(string,count)
k = 0
for i in count:
if int (i) > 1 :
print chr (k) + ", count = " + str (i)
k + = 1
string = "test string"
print printDups(string)
|
C#
using System;
class GFG
{
static int NO_OF_CHARS = 256;
static void fillCharCounts(String str,
int [] count)
{
for ( int i = 0; i < str.Length; i++)
count[str[i]]++;
}
static void printDups(String str)
{
int []count = new int [NO_OF_CHARS];
fillCharCounts(str, count);
for ( int i = 0; i < NO_OF_CHARS; i++)
if (count[i] > 1)
Console.WriteLine(( char )i + ", " +
"count = " + count[i]);
}
public static void Main()
{
String str = "test string" ;
printDups(str);
}
}
|
PHP
<?php
function fillCharCounts( $str , $count )
{
for ( $i = 0; $i < strlen ( $str ); $i ++)
$count [ord( $str [ $i ])]++;
for ( $i = 0; $i < 256; $i ++)
if ( $count [ $i ] > 1)
echo chr ( $i ) . ", " . "count = " .
( $count [ $i ]) . "\n" ;
}
function printDups( $str )
{
$count = array ();
for ( $i = 0; $i < 256; $i ++)
$count [ $i ] = 0;
fillCharCounts( $str , $count );
}
$str = "test string" ;
printDups( $str );
?>
|
Javascript
<script>
let NO_OF_CHARS = 256;
function printDups(str)
{
let count = new Array(NO_OF_CHARS);
count.fill(0);
for (let i = 0; i < str.length; i++)
count[str[i].charCodeAt()]++;
for (let i = 0; i < NO_OF_CHARS; i++)
{
if (count[i] > 1)
{
document.write(String.fromCharCode(i) + ", " +
"count = " + count[i] + "</br>" );
}
}
}
let str = "test string" ;
printDups(str);
</script>
|
Outputs, count = 2
t, count = 3
Time Complexity: O(n), where n = length of the string passed
Space Complexity: O(NO_OF_CHARS)
Note: Hashing involves the use of an array of fixed size each time no matter whatever the string is.
For example, str = “aaaaaaaaaa”.
An array of size 256 is used for str, only 1 block out of total size (256) will be utilized to store the number of occurrences of ‘a’ in str (i.e count[‘a’] = 10).
Rest 256 – 1 = 255 blocks remain unused.
Thus, Space Complexity is potentially high for such cases. So, to avoid any discrepancies and to improve Space Complexity, maps are generally preferred over long-sized arrays.
Method 2: Using Maps
Approach: The approach is the same as discussed in Method 1, but, using a map to store the count.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printDups(string str)
{
map< char , int > count;
for ( int i = 0; i < str.length(); i++) {
count[str[i]]++;
}
for ( auto it : count) {
if (it.second > 1)
cout << it.first << ", count = " << it.second
<< "\n" ;
}
}
int main()
{
string str = "test string" ;
printDups(str);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void printDups(String str)
{
HashMap<Character, Integer> count = new HashMap<>();
for ( int i = 0 ; i < str.length(); i++) {
if (!count.containsKey(str.charAt(i)))
count.put(str.charAt(i), 1 );
else
count.put(str.charAt(i),
count.get(str.charAt(i)) + 1 );
}
for (Map.Entry mapElement : count.entrySet()) {
char key = ( char )mapElement.getKey();
int value = (( int )mapElement.getValue());
if (value > 1 )
System.out.println(key
+ ", count = " + value);
}
}
public static void main(String[] args)
{
String str = "test string" ;
printDups(str);
}
}
|
Python3
from collections import defaultdict
def printDups(st):
count = defaultdict( int )
for i in range ( len (st)):
count[st[i]] + = 1
for it in count:
if (count[it] > 1 ):
print (it, ", count = " , count[it])
if __name__ = = "__main__" :
st = "test string"
printDups(st)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG{
static void printDups(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;
}
foreach ( var it in count.OrderBy(key => key.Value))
{
if (it.Value > 1)
Console.WriteLine(it.Key + ", count = " +
it.Value);
}
}
static public void Main()
{
String str = "test string" ;
printDups(str);
}
}
|
Javascript
<script>
function printDups(str)
{
var count = {};
for ( var i = 0; i < str.length; i++) {
count[str[i]] = 0;
}
for ( var i = 0; i < str.length; i++) {
count[str[i]]++;
}
for ( var it in count) {
if (count[it] > 1)
document.write(it + ", count = " + count[it] + "<br>" );
}
}
var str = "test string" ;
printDups(str);
</script>
|
Outputs, count = 2
t, count = 3
Time Complexity: O(N*log(N)), where N = length of the string passed and it generally takes O(log(N)) time for an element insertion in a map.
Space Complexity: O(K), where K = size of the map (0<=K<=input_string_length).
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
void printDups(string str)
{
unordered_map< char , int > count;
for ( int i = 0; i < str.length(); i++) {
count[str[i]]++;
}
for ( auto it : count) {
if (it.second > 1)
cout << it.first << ", count = " << it.second
<< "\n" ;
}
}
int main()
{
string str = "test string" ;
printDups(str);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static void printDups(String str)
{
Map<Character, Integer> count = new HashMap<>();
for ( int i = 0 ; i < str.length(); i++) {
if (count.containsKey(str.charAt(i)))
count.put(str.charAt(i) , count.get(str.charAt(i))+ 1 );
else count.put(str.charAt(i), 1 );
}
for (Map.Entry<Character,Integer> mapElement : count.entrySet()) {
if (mapElement.getValue() > 1 )
System.out.println(mapElement.getKey() + ", count = " + mapElement.getValue());
}
}
public static void main(String args[])
{
String str = "test string" ;
printDups(str);
}
}
|
Python3
def printDups( Str ):
count = {}
for i in range ( len ( Str )):
if ( Str [i] in count):
count[ Str [i]] + = 1
else :
count[ Str [i]] = 1
for it,it2 in count.items():
if (it2 > 1 ):
print ( str (it) + ", count = " + str (it2))
Str = "test string"
printDups( Str )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void printDups(String str)
{
SortedDictionary< char , int > count = new SortedDictionary< char , int >();
for ( int i = 0; i < str.Length; i++) {
if (count.ContainsKey(str[i]))
{
int temp = count[str[i]];
count.Remove(str[i]);
count.Add(str[i] , temp + 1);
}
else count.Add(str[i],1);
}
foreach (KeyValuePair< char , int > mapElement in count) {
if (mapElement.Value > 1)
Console.WriteLine(mapElement.Key + ", count = " + mapElement.Value);
}
}
public static void Main(String[] args)
{
String str = "test string" ;
printDups(str);
}
}
|
Javascript
<script>
function printDups(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);
}
}
for (let [it,it2] of count) {
if (it2 > 1)
document.write(it, ", count = " ,it2, "</br>" );
}
}
let str = "test string" ;
printDups(str);
</script>
|
Outputs, count = 2
t, count = 3
Time Complexity: O(N), where N = length of the string passed and it takes O(1) time to insert and access any element in an unordered map
Auxiliary Space: O(K), where K = size of the map (0<=K<=input_string_length).