Skip to content
Problem 1207 · LeetCode 1207(opens in a new tab)

Unique Number of Occurrences

EasyArrays

You are given a list of whole numbers, arr. Count how many times each distinct value shows up in it.

Return true if those counts are all different from each other, that is, no two distinct values appear the same number of times. Otherwise return false.

Example 1

Input:  arr = [4, 8, 4, 6, 8, 4]
Output: true
Why:    4 shows up 3 times, 8 twice, 6 once
2 more examples and the constraints

Example 2

Input:  arr = [3, 3, 7, 7]
Output: false
Why:    3 and 7 both show up twice

Example 3

Input:  arr = [-2, 0, -2]
Output: true
Why:    -2 shows up twice, 0 once

Constraints

  • 1 ≤ length of arr ≤ 1,000
  • −1,000 ≤ arr[i] ≤ 1,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Rescan and compare pairsO(n²)
  2. Count map + setO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 1,000 numbersVerdict
Rescan and compare pairsO(n²)
Works at this size; say why it is slow
Count map + setO(n)
Best; two short passes

n = length of arr.

Edge cases to test

  • One number. [9] has one value with one count, so nothing can tie: true.
  • Every value once. [1, 2] gives two counts of 1: false. Any list of two or more different values, each once, is false.
  • All the same value. [5, 5, 5] has a single count: true.
  • Negative values and zero. They are ordinary keys in the map; [-2, 0, -2] is true.

Common mistakes

  • Checking whether the values are unique instead of whether their counts are unique.
  • Adding a count to the set before checking it, so every count looks like a repeat.
  • Counting the same value more than once in the brute force, so it ties with itself.

How to talk through it

  1. 1Clarify. Do we compare counts of distinct values only? Can values be negative?
  2. 2Give the brute force. Count each value with a scan, compare every pair of counts; O(n²).
  3. 3Split the problem. First a frequency map, then a duplicate check on its values.
  4. 4Code it with a set. Check each count against the set before adding it.
  5. 5Test out loud. Run [1, 2] (false) and a single number (true) before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?