JavaScript Program to Print All Duplicate Characters in a String
Last Updated :
17 Jun, 2024
In this article, we will learn how to print all duplicate characters in a string in JavaScript. Given a string S, the task is to print all the duplicate characters with their occurrences in the given string.
Example:
Input: S = “geeksforgeeks”
Output:
e, count = 4
g, count = 2
k, count = 2
s, count = 2
Examples of Print All Duplicate Characters in a String In JavaScript
1. Using For Loop in JavaScript
In this approach, an object named charCount
to effectively maintain the frequency of characters in the string. It sequentially processes each character in the input string, increasing its count in the charCount
object. Once the character frequencies are established, the code then traverses through the charCount
object. It selectively prints characters that have occurrences greater than one, thereby accurately showcasing the duplicate characters along with the corresponding count of duplications.
Example: In this example, we are using a for loop.
JavaScript
function printDups(str) {
let charCount = {};
for (let i = 0; i < str.length; i++) {
let character = str[i];
charCount[character] =
(charCount[character] || 0) + 1;
}
for (let char in charCount) {
if (charCount[char] > 1) {
console.log(
char +
", count = " +
charCount[char]
);
}
}
}
let str = "geeksforgeeks";
printDups(str);
Outputg, count = 2
e, count = 4
k, count = 2
s, count = 2
2. Using Sorting in JavaScript
- Sort the given string.
- Loop through the sorted string to find the duplicates.
- If the next character is the same as the current character then we keep on counting the occurrence of that char.
- If the count is greater than one then we print the character and its count.
Example: In this example we are using Sorting
JavaScript
function printDuplicates(str) {
let len = str.length;
// Sorting the string
str = str.split('').sort().join('');
// Loop through the sorted string to find duplicates
for (let i = 0; i < len; i++) {
let count = 1;
// Counting the occurrences of each character
while (i < len - 1 && str[i] == str[i + 1]) {
count++;
i++;
}
// Printing the duplicate character and its count
if (count > 1) {
console.log(str[i] + ", count = " + count);
}
}
}
let str = "geeksforgeeks";
printDuplicates(str);
Outpute, count = 4
g, count = 2
k, count = 2
s, count = 2
3. Using Hashing in JavaScript
- Declare a unordered map of the char-int pair.
- Traverse the string using a loop and increase the count of the present char in the map.
- Iterate through the map and print a character that has a value greater than one in map.
Example: In this example we are using Hashing.
JavaScript
// JavaScript program to count all duplicates
// from string using maps
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);
}
//increase the count of characters by 1
}
//iterating through the unordered map
for (let [it, it2] of count) {
if (it2 > 1)
//if the count of characters is
//greater than 1 then duplicate found
console.log(it, ", count = ", it2);
}
}
/* Driver code*/
let str = "geeksforgeeks";
printDups(str);
Outputg , count = 2
e , count = 4
k , count = 2
s , count = 2
4. Using Set()
This approach uses two Sets to track characters in a string, seen set to store characters encountered, and duplicates set to store duplicate characters. It iterates over the string, adding characters to seen if they are not already there, or to duplicates if they are.
Example: In this example we are using Set().
JavaScript
function findDuplicates(str) {
const seen = new Set();
const duplicates = new Set();
for (let char of str) {
if (seen.has(char)) {
duplicates.add(char);
} else {
seen.add(char);
}
}
duplicates.forEach(char => {
const count = str.split(char).length - 1;
console.log(`${char}, count= ${count}`);
});
}
const str = "geeksforgeeks";
findDuplicates(str);
Outpute, count= 4
g, count= 2
k, count= 2
s, count= 2
5. Using Reduce Method in JavaScript
In this approach, we will use the reduce method to create an object that tracks the count of each character. Then, we will loop through this object to identify and print characters that have a count greater than one.
Example: Using the reduce Method
JavaScript
function printDupsUsingReduce(str) {
// Using reduce to build the character count object
let charCount = str.split('').reduce((acc, char) => {
acc[char] = (acc[char] || 0) + 1;
return acc;
}, {});
// Iterating over the charCount object to print duplicates
Object.keys(charCount).forEach(char => {
if (charCount[char] > 1) {
console.log(`${char}, count = ${charCount[char]}`);
}
});
}
let str = "geeksforgeeks";
printDupsUsingReduce(str);
Outputg, count = 2
e, count = 4
k, count = 2
s, count = 2
6. Using Filter Method in JavaScript
In this approach, we will use the filter method to identify characters that appear more than once in the string. This method will first create an array of characters from the string, then filter out the characters that appear only once, and finally count the occurrences of each duplicate character.
Example: Using the Filter Method
JavaScript
function printDupsUsingFilter(str) {
// Convert string to an array of characters
let chars = str.split('');
// Filter characters that appear more than once
let duplicates = chars.filter((char, index, arr) => arr.indexOf(char) !== arr.lastIndexOf(char));
// Create a set to get unique duplicate characters
let uniqueDups = new Set(duplicates);
// Count and print each unique duplicate character
uniqueDups.forEach(char => {
const count = str.split(char).length - 1;
console.log(`${char}, count = ${count}`);
});
}
let str = "geeksforgeeks";
printDupsUsingFilter(str);
Outputg, count = 2
e, count = 4
k, count = 2
s, count = 2
Similar Reads
JavaScript Program to Check for Repeated Characters in a String Here are the different methods to check for repeated characters in a string using JavaScript1. Using a Frequency Counter (Object)A frequency counter is one of the most efficient ways to check for repeated characters in a string. This approach involves iterating over the string and counting how often
3 min read
JavaScript Program to Find Kâth Non-Repeating Character in String The K'th non-repeating character in a string is found by iterating through the string length and counting how many times each character has appeared. When any character is found that appears only once and it is the K'th unique character encountered, it is returned as the result. This operation helps
6 min read
JavaScript Program to Find Missing Characters to Make a String Pangram We have given an input string and we need to find all the characters that are missing from the input string. We have to print all the output in the alphabetic order using JavaScript language. Below we have added the examples for better understanding. Examples: Input : welcome to geeksforgeeksOutput
6 min read
JavaScript Program to Get a Non-Repeating Character From the Given String In JavaScript, we can find the non-repeating character from the input string by identifying the characters that occur only once in the string. There are several approaches in JavaScript to get a non-repeating character from the given string which are as follows: Table of Content Using indexOf and la
3 min read
JavaScript Program Count number of Equal Pairs in a String In this article, we are going to learn how can we count a number of equal pairs in a string. Counting equal pairs in a string involves finding and counting pairs of consecutive characters that are the same. This task can be useful in various applications, including pattern recognition and data analy
3 min read
PHP Program to Print All Duplicate Characters in a String This article will show you how to print duplicate characters in a string using PHP. Detecting and printing duplicate characters in a string is a common task in programming. In this article, we will explore various approaches to achieve this.Table of ContentUsing array_count_values() FunctionUsing As
3 min read
JavaScript - How To Find Unique Characters of a String? Here are the various methods to find the unique characters of a string in JavaScript.1. Using Set (Most Common)The Set object is one of the easiest and most efficient ways to find unique characters. It automatically removes duplicates.JavaScriptconst s1 = "javascript"; const s2 = [...new Set(s1)]; c
3 min read
Javascript Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
5 min read
Java program to print all duplicate characters in a string Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}
2 min read
Print all the duplicate characters in a string 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 co
8 min read