KatInterview

Count Unique Elements in Array

Arrays & HashingAuto-graded · 22 test cases
EasyAuto-gradedArrays & Hashinghash-tablecountingfrequency-map

Last updated

Identify how many values appear exactly one time in an integer array using frequency analysis.

You are given an array of integers. Your task is to determine how many distinct values have a frequency of exactly one—that is, how many numbers appear precisely once in the entire array.

Write a function that takes an array of integers and returns the count of values that occur exactly once.

Constraints

  • The array length satisfies 0 ≤ len(numbers) ≤ 200,000.
  • Each integer is in the range [-1,000,000,000, 1,000,000,000].
  • If a value appears two or more times, it does not contribute to the count, regardless of where in the array those occurrences are located.
  • An empty array should return 0.
  • Target an expected time complexity of O(n).

Examples

Example 1

Input: count_unique_elements([4, 2, 1, 4, 4, 1, 3])

Output: 2

Example 2

Input: count_unique_elements([5, 5, -1, -1])

Output: 0

Hints

Hint 1

Build a complete frequency count first before deciding which values qualify—scanning left to right without tracking total occurrences can miss later duplicates.

Hint 2

A hash map (or Counter) lets you record how many times each distinct value appears in a single pass, then filter for counts equal to one.

Hint 3

The number of keys with frequency one is your answer, not the sum of the values themselves or the total number of distinct values.