Count Elements With Frequency One

Easy · Coding & Algorithms · Data Engineer · Technical Screen

Problem Statement

You are given an integer list numbers and asked to implement:

def count_single_occurrences(numbers: List[int]) -> int:

Compute and return how many values appear only one time across the full list.

  • Every integer whose total occurrence count in numbers equals 1 adds 1 to the returned total.
  • Any integer that shows up 2 or more times adds 0, whether its duplicate copies sit next to each other or at opposite ends of the list.
  • When numbers contains no elements, return 0.

Examples

Example 1

Input:  numbers = [7, -2, 5, 7, 0, -2, 9, 7]
Output: 3

Walk-through: Across the eight entries, 7 shows up three times and -2 shows up twice, so both are disqualified. The remaining values—5, 0, and 9—each occur a single time, giving a count of 3.

Example 2

Input:  numbers = [12, -8, 12, -8, 12]
Output: 0

Walk-through: 12 occurs three times and -8 occurs twice. Since no value has an overall count of 1, the function returns 0.

Constraints

  • 0 <= len(numbers) <= 200,000
  • -1,000,000,000 <= numbers[i] <= 1,000,000,000
  • Target time complexity: expected O(n), where n = len(numbers).

Step-by-step walkthrough

  1. Understand the goal

    We are given a list of integers numbers and need to return a single integer: how many distinct values appear only once across the entire list.

    A value's frequency is the total number of times it shows up in the list. Only values with a final frequency of 1 add to our result:

    numbers = [7, -2, 5, 7, 0, -2, 9, 7]
    
    Value   Occurrences   Contributes?
      7          3        No  (seen more than once)
     -2          2        No  (seen more than once)
      5          1        Yes
      0          1        Yes
      9          1        Yes
                          ---
    Total single-occurrence values = 3
    

    If every number repeats (like [12, -8, 12, -8, 12]) or the list is empty ([]), the answer is 0. The list can hold up to 200,000 integers between -1,000,000,000 and 1,000,000,000, and we want expected O(n) time.

  2. Why scanning per element or deciding early fails

    Two tempting shortcuts run into trouble right away:

    1. Rescanning the list for each value: For every distinct number v, calling numbers.count(v) walks the entire list from start to finish. If all 200,000 elements are distinct, that performs 200,000 * 200,000 = 40,000,000,000 comparisons (O(n^2) time), which is far too slow.
    2. Deciding the first time you see a number: When you read 9 at index 0 of [9, 1, 2, 3, 9], you cannot yet tell whether another 9 is waiting near the end of the list. You must finish reading every element before concluding that any number's total count is 1.
  3. Key idea: tally everything in a hash map first

    Why can't we just keep an array of counters indexed by value, like counts[value]? Because values span from -1,000,000,000 to 1,000,000,000 — over two billion possible numbers — even though at most 200,000 of them actually appear in numbers.

    Instead, we use a hash map (a dict in Python): a key-value lookup structure that stores only the numbers we actually see and finds or updates any key in O(1) expected time. That turns the problem into two clean passes:

    1. Pass 1 (Tally): Walk numbers from left to right and record the complete count of every value in counts.
    2. Pass 2 (Filter): Walk the values stored in counts and count how many equal 1.
  4. Pass 1: build the frequency map

    As we scan numbers, we check whether value is already a key in counts. If it is, we add 1 to its stored count; if this is the first time we have seen value, we initialize its count to 1.

    counts: Dict[int, int] = {}
    
    # Phase 1: Tally every occurrence across the entire array before making any decision,
    # because a duplicate of an early number can appear at the very end of the list.
    for value in numbers:
        if value in counts:
            counts[value] += 1
        else:
            counts[value] = 1
    
  5. Pass 2: count values with frequency equal to 1

    Once the first loop finishes, every key in counts is a distinct integer from numbers, and its mapped value is its complete frequency across the whole array. Now we simply loop over counts.values() and increment unique_count whenever frequency == 1.

    Notice how cleanly this handles edge cases: if numbers is empty, counts stays {} and unique_count stays 0; if a value appears 3 times (like [12, 12, 12]), frequency == 1 is False so it is ignored.

    # Phase 2: Count how many distinct numbers finished with a total frequency of 1.
    # Checking == 1 excludes values that appeared 2, 3, or more times.
    unique_count = 0
    for frequency in counts.values():
        if frequency == 1:
            unique_count += 1
    
  6. Trace through Example 1

    Let's trace numbers = [7, -2, 5, 7, 0, -2, 9, 7] through both passes:

    Pass 1 (reading left to right):
      index 0 -> value  7:  counts = {7: 1}
      index 1 -> value -2:  counts = {7: 1, -2: 1}        <- -2 looks solitary so far...
      index 2 -> value  5:  counts = {7: 1, -2: 1, 5: 1}
      index 3 -> value  7:  counts = {7: 2, -2: 1, 5: 1}
      index 4 -> value  0:  counts = {7: 2, -2: 1, 5: 1, 0: 1}
      index 5 -> value -2:  counts = {7: 2, -2: 2, 5: 1, 0: 1}  <- second -2 disqualifies -2!
      index 6 -> value  9:  counts = {7: 2, -2: 2, 5: 1, 0: 1, 9: 1}
      index 7 -> value  7:  counts = {7: 3, -2: 2, 5: 1, 0: 1, 9: 1}
    
    Pass 2 (checking final frequencies in counts.values()):
       7 -> frequency 3  (skip)
      -2 -> frequency 2  (skip)
       5 -> frequency 1  (unique_count = 1)
       0 -> frequency 1  (unique_count = 2)
       9 -> frequency 1  (unique_count = 3)
    
    Return: 3
    
  7. Complete solution

    Putting both passes inside count_single_occurrences gives the full solution:

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_single_occurrences(numbers: List[int]) -> int:
        # counts: dict mapping integer_value -> total_occurrences (e.g. {7: 3, -2: 2, 5: 1, 0: 1, 9: 1})
        counts: Dict[int, int] = {}
    
        # Phase 1: Tally every occurrence across the entire array before making any decision,
        # because a duplicate of an early number can appear at the very end of the list.
        for value in numbers:
            if value in counts:
                counts[value] += 1
            else:
                counts[value] = 1
    
        # Phase 2: Count how many distinct numbers finished with a total frequency of 1.
        # Checking == 1 excludes values that appeared 2, 3, or more times.
        unique_count = 0
        for frequency in counts.values():
            if frequency == 1:
                unique_count += 1
    
        return unique_count
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine counting paper ballots out of a ballot box to find out how many write-in candidates received only a single vote. When you pull out the very first slip for "Alice", you cannot immediately mark Alice as a single-vote candidate — another slip for Alice might be sitting at the very bottom of the box. The reliable method is to empty the entire box onto a tally sheet first, adding one tally mark next to a name each time it appears, and only after the box is empty count how many names have a final tally of 1.

Our tally sheet in code is a hash map (dict in Python) — a key-value lookup table that finds or updates any key in O(1) average time — mapping each integer to its frequency (the total number of times that integer appears in the array). Why do simpler-looking approaches fall short? If we check each element by rescanning the array with numbers.count(x), we repeat full scans over and over for O(n^2) total work — up to 40,000,000,000 comparisons when n = 200,000. And if we try to decide whether a number is unique during a single left-to-right scan without storing full counts, any duplicate separated from its first copy (like 7 at both ends of [7, -2, 5, 7]) tricks us into an early wrong decision, while allocating a direct-indexed counter array across -10^9 .. 10^9 would waste gigabytes of memory.

Here is how the two-pass tally works on numbers = [7, -2, 5, 7]:

Pass 1 — read every element into counts:
  see  7 -> counts = {7: 1}
  see -2 -> counts = {7: 1, -2: 1}
  see  5 -> counts = {7: 1, -2: 1, 5: 1}
  see  7 -> counts = {7: 2, -2: 1, 5: 1}   <- second 7 updates frequency to 2

Pass 2 — count keys whose final frequency == 1:
   7 has frequency 2 -> skip
  -2 has frequency 1 -> unique_count = 1
   5 has frequency 1 -> unique_count = 2   -> return 2

Complexity

Let n be the length of numbers and d be the number of distinct integers in numbers (d <= n).

  • Time: expected O(n). Pass 1 scans all n integers once and performs one O(1) expected-time dictionary lookup and update per integer; Pass 2 iterates over the d entries in counts, which is at most n checks.
  • Space: O(d) (O(n) in the worst case when every integer is unique). The counts dictionary stores one key-value pair per distinct integer seen in numbers.

Edge cases

  • Empty list []: Pass 1 does zero iterations, counts remains empty, and Pass 2 returns 0 without needing a special if not numbers check.
  • Single-element list [7]: counts becomes {7: 1}, returning 1.
  • Separated duplicates ([9, 1, 2, 3, 9]): Because no decision is made until Pass 1 finishes, the trailing 9 raises counts[9] to 2 and only 1, 2, and 3 are counted (returning 3).
  • Odd repeat counts ([5, 5, 5]): counts[5] becomes 3, and frequency == 1 is False, correctly returning 0.
  • Negative numbers, zero, and ±1,000,000,000: Python dictionaries hash negative integers, 0, and large integers directly as keys with no index-shifting required.
  • All duplicates ([12, -8, 12, -8, 12]): Every stored frequency is at least 2, returning 0.

Common mistakes

  • Counting values on first sight: Incrementing the answer the first time a number appears overcounts any value whose duplicate arrives later in the array.
  • Toggling a set on each occurrence: Adding x when unseen and removing x when seen again actually counts values with an odd frequency (1, 3, 5, ...), so [5, 5, 5] ends with {5} in the set and wrongly returns 1 instead of 0.
  • Returning len(set(numbers)): A set counts how many distinct numbers exist (frequency >= 1), whereas we want only numbers with frequency == 1.
  • Checking only adjacent neighbors without sorting: Comparing numbers[i] against numbers[i - 1] and numbers[i + 1] misses separated duplicates like [7, 5, 7] unless the array has been sorted first.
  • Calling numbers.count(v) inside a loop: Even if you loop over set(numbers), each .count(v) call rescans the entire n-element list, turning linear work into O(n * d) and timing out on large inputs.

Alternative approaches

  • collections.Counter: Python's standard library Counter(numbers) builds the exact same value -> frequency dictionary in C under the hood; you still run Pass 2 (sum(1 for freq in Counter(numbers).values() if freq == 1)) in expected O(n) time and O(d) space.
  • Sort first, then check neighbors (O(n log n) time): Sorting sorted_nums = sorted(numbers) groups identical values into contiguous runs, so an element at index i has frequency 1 if and only if it differs from both sorted_nums[i - 1] (when i > 0) and sorted_nums[i + 1] (when i + 1 < n). This avoids hash collisions and gives worst-case O(n log n) time, though it is slower than expected O(n) hashing and sorted(...) still uses O(n) space.

Follow-up questions

  • How would you return the single-occurrence values in their original left-to-right order? Keep Pass 1 identical so counts holds every final frequency, then in Pass 2 loop over the original numbers list instead of counts.values() and append value whenever counts[value] == 1. Because each qualifying value appears only once in numbers, iterating numbers preserves exact arrival order with no extra deduplication, keeping expected O(n) time and O(n) space.
  • How could you optimize time and memory if every input integer lay between 0 and 1,000? Replace the hash map with a fixed-size list counts = [0] * 1001 indexed directly by value. Array indexing avoids hashing overhead and hash collisions altogether, guaranteeing strict worst-case O(n + U) time and O(U) space where U = 1001 is the value range size.
  • How could you solve the variant where every integer appears twice except one lone number using O(1) extra space? Combine every element using XOR (^) — the bitwise exclusive-OR operator that compares two integers bit by bit and outputs 1 where bits differ and 0 where bits match. Because x ^ x == 0, x ^ 0 == x, and XOR is order-independent, every duplicate pair cancels out to 0 and leaves the lone number; however, that trick fails on our general problem where numbers can appear 3 times or multiple distinct numbers can appear once.

Follow-up questions

Similar questions

More Agoda interview questions

All 7 Agoda questions →