Print all the duplicates in the input string - GeeksforGeeks

23 Nov, 2021
Write an efficient program to print all the duplicates and their counts in the input string 
Method 1: Using hashingAlgorithm: Let input string be “geeksforgeeks” 1: Construct character count array from the input string.count[‘e’] = 4 count[‘g’] = 2 count[‘k’] = 2 ......2: Print all the indexes from the constructed array which have values greater than 1.Solution 
C++14
C
Java
Python
C#
PHP
Javascript
// C++ program to count all duplicates// from string using hashing#include <iostream>using namespace std;# define NO_OF_CHARS 256 class gfg{    public :         /* Fills count array with    frequency of characters */    void fillCharCounts(char *str, int *count)    {        int i;        for (i = 0; *(str + i); i++)        count[*(str + i)]++;    }     /* Print duplicates present    in the passed string */    void printDups(char *str)    {                 // Create an array of size 256 and fill        // count of every character in it        int *count = (int *)calloc(NO_OF_CHARS,                                      sizeof(int));        fillCharCounts(str, count);         // Print characters having count more than 0        int i;        for (i = 0; i < NO_OF_CHARS; i++)        if(count[i] > 1)            printf("%c, count = %d \n", i, count[i]);         free(count);    }}; /* Driver code*/int main(){    gfg g ;    char str[] = "test string";    g.printDups(str);    //getchar();    return 0;} // This code is contributed by SoM15242
// C program to count all duplicates// from string using hashing# include <stdio.h># include <stdlib.h># define NO_OF_CHARS 256 /* Fills count array with   frequency of characters */void fillCharCounts(char *str, int *count){   int i;   for (i = 0; *(str+i);  i++)      count[*(str+i)]++;} /* Print duplicates present   in the passed string */void printDups(char *str){     // Create an array of size 256 and  // fill count of every character in it  int *count = (int *)calloc(NO_OF_CHARS,                             sizeof(int));  fillCharCounts(str, count);   // Print characters having count more than 0  int i;  for (i = 0; i < NO_OF_CHARS; i++)    if(count[i] > 1)        printf("%c,  count = %d \n", i,  count[i]);   free(count);} /* Driver program to test to print printDups*/int main(){    char str[] = "test string";    printDups(str);    getchar();    return 0;}
// Java program to count all// duplicates from string using// hashing public class GFG {    static final int NO_OF_CHARS = 256;     /* Fills count array with       frequency of characters */    static void fillCharCounts(String str,                                   int[] count)    {        for (int i = 0; i < str.length(); i++)            count[str.charAt(i)]++;    }     /* Print duplicates present      in the passed string */    static void printDups(String str)    {        // Create an array of size        // 256 and fill count of        // every character in it        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]);    }     // Driver Method    public static void main(String[] args)    {        String str = "test string";        printDups(str);    }}
# Python program to count all# duplicates from string using hashingNO_OF_CHARS = 256 # Fills count array with# frequency of charactersdef fillCharCounts(string, count):    for i in string:        count[ord(i)] += 1    return count # Print duplicates present# in the passed stringdef printDups(string):         # Create an array of size 256    # and fill count of every character in it    count = [0] * NO_OF_CHARS    count = fillCharCounts(string,count)     # Utility Variable    k = 0     # Print characters having    # count more than 0    for i in count:        if int(i) > 1:            print chr(k) + ", count = " + str(i)        k += 1 # Driver program to test the above functionstring = "test string"print printDups(string) # This code is contributed by Bhavya Jain
// C# program to count all duplicates// from string using hashingusing System; class GFG{         static int NO_OF_CHARS = 256;         /* Fills count array with       frequency of characters */    static void fillCharCounts(String str,                                 int[] count)    {        for (int i = 0; i < str.Length; i++)            count[str[i]]++;    }         /* Print duplicates present in    the passed string */    static void printDups(String str)    {                 // Create an array of size 256 and        // fill count of every character in it        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]);    }         // Driver Method    public static void Main()    {        String str = "test string";        printDups(str);    }} // This code is contributed by Sam007
<?php// PHP program to count// all duplicates from// string using hashingfunction 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";} // Print duplicates present// in the passed stringfunction printDups($str){    // Create an array of size    // 256 and fill count of    // every character in it    $count = array();    for ($i = 0; $i < 256; $i++)    $count[$i] = 0;    fillCharCounts($str, $count);      } // Driver Code$str = "test string";printDups($str);     // This code is contributed by Sam007?>
<script>    // Javascript program to count all duplicates    // from string using hashing         let NO_OF_CHARS = 256;          /* Print duplicates present in    the passed string */    function printDups(str)    {                  // Create an array of size 256 and        // fill count of every character in it        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>
s, 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.
Solution:
C++
Java
Python3
C#
Javascript
// C++ program to count all duplicates// from string using maps#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";    }}/* Driver code*/int main(){    string str = "test string";    printDups(str);    return 0;}// This code is contributed by yashbeersingh42
// Java program to count all duplicates// from string using mapsimport java.util.*; class GFG {     static void printDups(String str)    {        HashMap<Character, Integer> count = new HashMap<>();        /*Store duplicates present        in the passed string */        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);        }         /*Print duplicates in sorted order*/        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);        }    }    // Driver code    public static void main(String[] args)    {        String str = "test string";        printDups(str);    }}// This code is contributed by yashbeersingh42
# Python 3 program to count all duplicates# from string using mapsfrom 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]) # Driver codeif __name__ == "__main__":     st = "test string"    printDups(st)     # This code is contributed by ukasp.
// C# program to count all duplicates// from string using mapsusing 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);    }} // Driver codestatic public void Main(){    String str = "test string";    printDups(str);}} // This code is contributed by shubhamsingh10
<script>//Javascript Implementation//  to count all duplicates// from string using maps 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>");    }}/* Driver code*/var str = "test string";printDups(str); // This code is contributed by shubhamsingh10</script>
s, count = 2
t, count = 3
Time Complexity: O(N log N), where N = length of the string passed and it generally takes logN time for an element insertion in a map.
Space Complexity: O(K), where K = size of the map (0<=K<=input_string_length).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
YouTubeGeeksforGeeks506K subscribersPrint all the duplicates in the input string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=KYVR5U7rwAE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
C++
// C++ program to count all duplicates// from string using maps#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]]++;  //increase the count of characters by 1    }      for (auto it : count) {   //iterating through the unordered map        if (it.second > 1)   //if the count of characters is greater then 1 then duplicate found            cout << it.first << ", count = " << it.second                 << "\n";    }}/* Driver code*/int main(){    string str = "test string";    printDups(str);    return 0;}
s, 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
Space Complexity:
 O(K), where K = size of the map (0<=K<=input_string_length).
Sam007
manoprakash6
SoumikMondal
saxenakg
yashbeersingh42
decode2207
ukasp
SHUBHAMSINGH10
rupeshsk30
singghakshay
String Duplicates
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Length of the longest substring without repeating characters
Top 50 String Coding Problems for Interviews
Remove duplicates from a given string
How to split a string in C/C++, Python and Java?
Reverse words in a given string