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],
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read