Find duplicate characters in a string
Problem
Print every character that appears more than once in the string, together with how many times it appears.
Example 1
Input: "programming" Output: r: 2, g: 2, m: 2
Also asked as: Find Duplicate characters in a string
Test cases
Case 1
Input: "programming"
Expected: [{"char":"r","count":2},{"char":"g","count":2},{"char":"m","count":2}]Case 2
Input: "aabbb"
Expected: [{"char":"a","count":2},{"char":"b","count":3}]Case 3
Input: "abc" Expected: []
Case 4
Input: "" Expected: []
View solutionHide solution1 approach
1. Frequency map
Time O(n)Space O(k)
Count each character; report those with count > 1.
function duplicates(s) { const freq = new Map(); for (const c of s) freq.set(c, (freq.get(c) || 0) + 1); return [...freq].filter(([, n]) => n > 1).map(([c, n]) => ({ char: c, count: n }));}