Print all the duplicate characters in a string
Last Updated :
12 Jun, 2025
Given a string s, the task is to identify all characters that appear more than once and print each as a list containing the character and its count.
Examples:
Input: s = "geeksforgeeks"
Output: ['e', 4], ['g', 2], ['k', 2], ['s', 2]
Explanation: Characters e, g, k, and s appear more than once. Their counts are shown in order of first occurrence.
Input: s = "programming"
Output: ['r', 2], ['g', 2], ['m', 2]
Explanation: Only r, g, and m are duplicates. Output lists them with their counts.
Input: s = "mississippi"
Output: ['i', 4], ['s', 4], ['p', 2]
Explanation: Characters i, s, and p have multiple occurrences. The output reflects that with count and order preserved.
[Approach - 1] Using Sorting - O(n*log(n)) Time and O(1) Space
The idea is to group same characters together by sorting the string first. This makes it easier to count consecutive duplicates in one pass. As we traverse the sorted string, we increment a counter for each matching character, and only print those with count > 1. Sorting helps eliminate the need for extra space like maps or arrays, making the logic clean and space-efficient.
C++
// C++ Code to print duplicate characters
// and their counts using Sorting
#include <bits/stdc++.h>
using namespace std;
// Function to print duplicate characters with their count
void printDuplicates(string s) {
// Sort the string to group same characters together
sort(s.begin(), s.end());
// Traverse the sorted string to count duplicates
for (int i = 0; i < s.length();) {
int count = 1;
// Count occurrences of current character
while (i + count < s.length() && s[i] == s[i + count]) {
count++;
}
// If count > 1, print the character and its count
if (count > 1) {
cout << "['" << s[i] << "', " << count << "], ";
}
// Move to the next different character
i += count;
}
}
int main() {
string s = "geeksforgeeks";
printDuplicates(s);
return 0;
}
Java
// Java Code to print duplicate characters
// and their counts using Sorting
import java.util.*;
class GfG {
// Function to print duplicate characters with their count
static void printDuplicates(String s) {
// Convert string to character array
char[] arr = s.toCharArray();
// Sort the string to group same characters together
Arrays.sort(arr);
// Traverse the sorted string to count duplicates
for (int i = 0; i < arr.length;) {
int count = 1;
// Count occurrences of current character
while (i + count < arr.length && arr[i] == arr[i + count]) {
count++;
}
// If count > 1, print the character and its count
if (count > 1) {
System.out.print("['" + arr[i] + "', " + count + "], ");
}
// Move to the next different character
i += count;
}
}
public static void main(String[] args) {
String s = "geeksforgeeks";
printDuplicates(s);
}
}
Python
# Python Code to print duplicate characters
# and their counts using Sorting
# Function to print duplicate characters with their count
def printDuplicates(s):
# Sort the string to group same characters together
s = ''.join(sorted(s))
# Traverse the sorted string to count duplicates
i = 0
while i < len(s):
count = 1
# Count occurrences of current character
while i + count < len(s) and s[i] == s[i + count]:
count += 1
# If count > 1, print the character and its count
if count > 1:
print(["" + s[i] + "", count], end=", ")
# Move to the next different character
i += count
if __name__ == "__main__":
s = "geeksforgeeks"
printDuplicates(s)
C#
// C# Code to print duplicate characters
// and their counts using Sorting
using System;
class GfG {
// Function to print duplicate characters with their count
static void printDuplicates(string s) {
// Convert string to character array
char[] arr = s.ToCharArray();
// Sort the string to group same characters together
Array.Sort(arr);
// Traverse the sorted string to count duplicates
for (int i = 0; i < arr.Length;) {
int count = 1;
// Count occurrences of current character
while (i + count < arr.Length && arr[i] == arr[i + count]) {
count++;
}
// If count > 1, print the character and its count
if (count > 1) {
Console.Write("['" + arr[i] + "', " + count + "], ");
}
// Move to the next different character
i += count;
}
}
static void Main() {
string s = "geeksforgeeks";
printDuplicates(s);
}
}
JavaScript
// JavaScript Code to print duplicate characters
// and their counts using Sorting
// Function to print duplicate characters with their count
function printDuplicates(s) {
// Convert string to array and sort to group same characters
s = s.split('').sort().join('');
// Traverse the sorted string to count duplicates
let i = 0;
while (i < s.length) {
let count = 1;
// Count occurrences of current character
while (i + count < s.length && s[i] === s[i + count]) {
count++;
}
// If count > 1, print the character and its count
if (count > 1) {
console.log(["" + s[i] + "", count]);
}
// Move to the next different character
i += count;
}
}
// Driver Code
let s = "geeksforgeeks";
printDuplicates(s);
Output['e', 4], ['g', 2], ['k', 2], ['s', 2],
[Approach - 2] Using Hashing - O(n) Time
The idea is to count how many times each character appears using a hash map, which allows for efficient lookups and updates. The thought process is that repeated characters will have a count > 1, and we can detect them in a single pass. Hashing ensures we achieve O(n) time by avoiding nested comparisons or sorting. This method is optimal for large strings where frequency tracking is more efficient than sorting-based grouping.
The auxiliary space requirement of this solution is O(ALPHABET_SIZE). For lower case characters, the value of ALPHABET_SIZE is 26 which is a constant.
C++
// C++ Code to print duplicate characters
// and their counts using Hashing
#include <bits/stdc++.h>
using namespace std;
// Function to print duplicate characters with their count
void printDuplicates(string s) {
// Hash map to store frequency of each character
unordered_map<char, int> freq;
// Count frequency of each character
for (char c : s) {
freq[c]++;
}
// Traverse the map and print characters with count > 1
for (auto it : freq) {
if (it.second > 1) {
cout << "['" << it.first << "', " << it.second << "], ";
}
}
}
int main() {
string s = "geeksforgeeks";
printDuplicates(s);
return 0;
}
Java
// Java Code to print duplicate characters
// and their counts using Hashing
import java.util.*;
class GfG {
// Function to print duplicate characters with their count
public static void printDuplicates(String s) {
// Hash map to store frequency of each character
HashMap<Character, Integer> freq = new HashMap<>();
// Count frequency of each character
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
// Traverse the map and print characters with count > 1
for (Map.Entry<Character, Integer> it : freq.entrySet()) {
if (it.getValue() > 1) {
System.out.print("['" + it.getKey() + "', " + it.getValue() + "], ");
}
}
}
public static void main(String[] args) {
String s = "geeksforgeeks";
printDuplicates(s);
}
}
Python
# Python Code to print duplicate characters
# and their counts using Hashing
# Function to print duplicate characters with their count
def printDuplicates(s):
# Hash map to store frequency of each character
freq = {}
# Count frequency of each character
for c in s:
freq[c] = freq.get(c, 0) + 1
# Traverse the map and print characters with count > 1
for key in freq:
if freq[key] > 1:
print(["{}".format(key), freq[key]], end=", ")
if __name__ == "__main__":
s = "geeksforgeeks"
printDuplicates(s)
C#
// C# Code to print duplicate characters
// and their counts using Hashing
using System;
using System.Collections.Generic;
class GfG {
// Function to print duplicate characters with their count
public static void printDuplicates(string s) {
// Hash map to store frequency of each character
Dictionary<char, int> freq = new Dictionary<char, int>();
// Count frequency of each character
foreach (char c in s) {
if (freq.ContainsKey(c)) {
freq[c]++;
} else {
freq[c] = 1;
}
}
// Traverse the map and print characters with count > 1
foreach (KeyValuePair<char, int> it in freq) {
if (it.Value > 1) {
Console.Write("['" + it.Key + "', " + it.Value + "], ");
}
}
}
static void Main() {
string s = "geeksforgeeks";
printDuplicates(s);
}
}
JavaScript
// JavaScript Code to print duplicate characters
// and their counts using Hashing
// Function to print duplicate characters with their count
function printDuplicates(s) {
// Hash map to store frequency of each character
let freq = {};
// Count frequency of each character
for (let c of s) {
if (freq[c]) {
freq[c]++;
} else {
freq[c] = 1;
}
}
// Traverse the map and print characters with count > 1
for (let key in freq) {
if (freq[key] > 1) {
console.log(["" + key, freq[key]]);
}
}
}
// Driver Code
let s = "geeksforgeeks";
printDuplicates(s);
Output['g', 2], ['e', 4], ['k', 2], ['s', 2],