~/problems / Arrays & hashing / Complexity analysis

Count distinct values

easy ~10 min

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].
  • Comparing each element against all earlier ones is O(n²) and too slow at this size. Aim for 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