progress

~/problems / Arrays & hashing / Complexity analysis

Count distinct values

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write count_distinct(nums) that returns how many different values appear in the list nums.

  • len(nums) is between 0 and 200,000; values are integers in [1, 10^9].
  • ⭐ Bonus: comparing each element against all earlier ones is O(n²) and still passes; a speed test with 200,000 values earns a star in O(n) expected or O(n log n).
count_distinct([7, 3, 7, 7, 1])   # 3
count_distinct([])                # 0
Show hint

there are two standard ways: a hash set of values seen (O(n) expected), or sort and count the positions where the value changes (O(n log n)). Know why both work.

Topic: Complexity analysis. Big-O from constraints: n = 10^5 means O(n log n); know the Python constant factors.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc