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
numbersequals1adds1to the returned total. - Any integer that shows up
2or more times adds0, whether its duplicate copies sit next to each other or at opposite ends of the list. - When
numberscontains no elements, return0.
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), wheren = len(numbers).
Step-by-step walkthrough
Understand the goal
We are given a list of integers
numbersand 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
1add 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 = 3If every number repeats (like
[12, -8, 12, -8, 12]) or the list is empty ([]), the answer is0. The list can hold up to200,000integers between-1,000,000,000and1,000,000,000, and we want expectedO(n)time.Why scanning per element or deciding early fails
Two tempting shortcuts run into trouble right away:
- Rescanning the list for each value: For every distinct number
v, callingnumbers.count(v)walks the entire list from start to finish. If all200,000elements are distinct, that performs200,000 * 200,000 = 40,000,000,000comparisons (O(n^2)time), which is far too slow. - Deciding the first time you see a number: When you read
9at index0of[9, 1, 2, 3, 9], you cannot yet tell whether another9is waiting near the end of the list. You must finish reading every element before concluding that any number's total count is1.
- Rescanning the list for each value: For every distinct number
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,000to1,000,000,000— over two billion possible numbers — even though at most200,000of them actually appear innumbers.Instead, we use a hash map (a
dictin Python): a key-value lookup structure that stores only the numbers we actually see and finds or updates any key inO(1)expected time. That turns the problem into two clean passes:- Pass 1 (Tally): Walk
numbersfrom left to right and record the complete count of every value incounts. - Pass 2 (Filter): Walk the values stored in
countsand count how many equal1.
- Pass 1 (Tally): Walk
Pass 1: build the frequency map
As we scan
numbers, we check whethervalueis already a key incounts. If it is, we add1to its stored count; if this is the first time we have seenvalue, we initialize its count to1.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] = 1Pass 2: count values with frequency equal to 1
Once the first loop finishes, every key in
countsis a distinct integer fromnumbers, and its mapped value is its complete frequency across the whole array. Now we simply loop overcounts.values()and incrementunique_countwheneverfrequency == 1.Notice how cleanly this handles edge cases: if
numbersis empty,countsstays{}andunique_countstays0; if a value appears3times (like[12, 12, 12]),frequency == 1isFalseso 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 += 1Trace 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: 3Complete solution
Putting both passes inside
count_single_occurrencesgives 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 allnintegers once and performs oneO(1)expected-time dictionary lookup and update per integer; Pass 2 iterates over thedentries incounts, which is at mostnchecks. - Space:
O(d)(O(n)in the worst case when every integer is unique). Thecountsdictionary stores one key-value pair per distinct integer seen innumbers.
Edge cases
- Empty list
[]: Pass 1 does zero iterations,countsremains empty, and Pass 2 returns0without needing a specialif not numberscheck. - Single-element list
[7]:countsbecomes{7: 1}, returning1. - Separated duplicates (
[9, 1, 2, 3, 9]): Because no decision is made until Pass 1 finishes, the trailing9raisescounts[9]to2and only1,2, and3are counted (returning3). - Odd repeat counts (
[5, 5, 5]):counts[5]becomes3, andfrequency == 1isFalse, correctly returning0. - 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 least2, returning0.
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
seton each occurrence: Addingxwhen unseen and removingxwhen seen again actually counts values with an odd frequency (1, 3, 5, ...), so[5, 5, 5]ends with{5}in the set and wrongly returns1instead of0. - 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]againstnumbers[i - 1]andnumbers[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 overset(numbers), each.count(v)call rescans the entiren-element list, turning linear work intoO(n * d)and timing out on large inputs.
Alternative approaches
collections.Counter: Python's standard libraryCounter(numbers)builds the exact samevalue -> frequencydictionary in C under the hood; you still run Pass 2 (sum(1 for freq in Counter(numbers).values() if freq == 1)) in expectedO(n)time andO(d)space.- Sort first, then check neighbors (
O(n log n)time): Sortingsorted_nums = sorted(numbers)groups identical values into contiguous runs, so an element at indexihas frequency1if and only if it differs from bothsorted_nums[i - 1](wheni > 0) andsorted_nums[i + 1](wheni + 1 < n). This avoids hash collisions and gives worst-caseO(n log n)time, though it is slower than expectedO(n)hashing andsorted(...)still usesO(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
countsholds every final frequency, then in Pass 2 loop over the originalnumberslist instead ofcounts.values()and appendvaluewhenevercounts[value] == 1. Because each qualifying value appears only once innumbers, iteratingnumberspreserves exact arrival order with no extra deduplication, keeping expectedO(n)time andO(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] * 1001indexed directly byvalue. Array indexing avoids hashing overhead and hash collisions altogether, guaranteeing strict worst-caseO(n + U)time andO(U)space whereU = 1001is 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 outputs1where bits differ and0where bits match. Becausex ^ x == 0,x ^ 0 == x, and XOR is order-independent, every duplicate pair cancels out to0and leaves the lone number; however, that trick fails on our general problem where numbers can appear3times or multiple distinct numbers can appear once.
Follow-up questions
- How would you return the single-occurrence values in their original left-to-right order?
- How could you optimize time and memory if every input integer lay between 0 and 1,000?
- How could you solve the variant where every integer appears twice except one lone number using O(1) extra space?
Similar questions
- Minimum Triangle Path Sum and Two-Dice Stopping Analysis
- Locate Two Array Indices With a Target Sum
- Probability of Two Uniform Arrivals Meeting
- Longest Consecutive Full-Attendance Day Streak
- Top Monthly Customers Under Competition Ranking
- Assign Mapped or Fallback Unique IDs to Employees
More Agoda interview questions
- Longest Consecutive Full-Attendance Day Streak Easy
- Top Monthly Customers Under Competition Ranking Easy
- Assign Mapped or Fallback Unique IDs to Employees Easy Pro
- Probability of Two Uniform Arrivals Meeting Medium Pro
- Minimum Triangle Path Sum and Two-Dice Stopping Analysis Medium Pro
- Locate Two Array Indices With a Target Sum Medium Pro