Print all the duplicate characters in a string
Given a string, find all characters that appear more than once and print each duplicate character along with its count.
The comparison is case-sensitive — 'a' and 'A' are treated as different characters.
Examples
Input: "programming"
Output: { r: 2, g: 2, m: 2 }
Input: "hello world"
Output: { l: 3, o: 2 }
Input: "abcde"
Output: {} (no duplicates)
Constraints
- The string can contain letters, digits, spaces, and special characters.
- An empty string should return no duplicates.
Sample Input
s = "test string"
Sample Output
t: 3, s: 2
Constraints
- 1 <= s.length <= 10^5
- s consists of printable ASCII characters
Topics
Count each character's frequency using a hash map in a single pass. Then filter for characters with a count greater than one.
function findDuplicates(str) {
const freq = {};
for (const ch of str) {
freq[ch] = (freq[ch] || 0) + 1;
}
const duplicates = {};
for (const [ch, count] of Object.entries(freq)) {
if (count > 1) {
duplicates[ch] = count;
}
}
return duplicates;
}
Time: O(n) — single pass to count, single pass to filter. Space: O(k) where k is the number of distinct characters.
Saved in this browser only. Private to you.