Print all the duplicate characters in a string
You're given a string. Identify every character that shows up more than once, and report each one together with how many times it occurs.
Treat uppercase and lowercase as distinct characters — 'a' and 'A' don't count as the same.
Input Format
Implement findDuplicates(str). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 · Run Sample
Input
str = "programming" Output
{"r":2,"g":2,"m":2} Example 2
Input
str = "" Output
{} Constraints
- 0 <= str.length <= 10^5
- str consists of printable ASCII characters.
Test Cases (2)
Case 1
Args: ["programming"]
Expected: {"r":2,"g":2,"m":2}
Case 2
Args: [""]
Expected: {}
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.