Skip to problem
←

Duplicate Character Counts

Easy 0 attempts

Given a string str, return an object containing every character that occurs more than once, mapped to its total number of occurrences.

Count characters exactly as written. Uppercase and lowercase are distinct, and spaces, digits, and punctuation count too. Include each repeated character once as a property; omit characters occurring only once. Property order does not matter.

For str = "aAa! ", return {"a": 2}. For str = "aaa", return {"a": 3}, not {"a": 2}: report the total count, not the number of repetitions after the first occurrence. Return {} for an empty string or one with no duplicates. Return the object rather than printing it.

Function contract

Implement findDuplicates(str).

Output: Return an object mapping each character occurring at least twice to its total occurrence count. Return {} if none repeat; property order does not matter.

Example 1

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.

Count, Then Filter

Scan every character and increment its frequency. Do not normalize letter case or trim spaces: the contract treats each printable ASCII character separately.

In a second pass over the frequency entries, copy only counts greater than one to the result. This reports each repeated character exactly once with its full count. An empty input or all-distinct input naturally produces an empty object.

javascript
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, including the result. Under the printable ASCII constraint, k is at most 95, so space is bounded independently of input length.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript