Find Single Number Appearing Once in Python

Count frequency of each number in a list and return the one that appears exactly once when all others appear twice.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

13 lines
Python 3.9+
from collections import Counter

def find_single_number(nums):
    counts = Counter(nums)
    for num, count in counts.items():
        if count == 1:
            return num
    return None

if __name__ == "__main__":
    nums = [4, 1, 2, 1, 2]
    result = find_single_number(nums)
    print(f"Single number in {nums} is: {result}")

Output

stdout
Single number in [4, 1, 2, 1, 2] is: 4

How it works

The Counter from the collections module builds a dictionary mapping each number to its frequency. Iterating over the items, the loop checks whether a count equals 1 and returns the associated number immediately. This works because the problem guarantees exactly one number appears once. Using Counter gives O(n) time and O(n) space, which is simple and readable for typical input sizes.

Common mistakes

  • Assuming the input list is non-empty; handle `None` or empty list gracefully.
  • Returning the first number with count 1 incorrectly if counts are not normalized.
  • Using a set-based approach that works only for small constraints and misses the single number if duplicates are not exactly twice.

Variations

  1. Use XOR bitwise operation to find the single number in O(n) time and O(1) space.
  2. Sort the list and check adjacent elements for a linear-time solution with O(n log n) time.

Real-world use cases

  • Identify the odd record in a transaction log where each customer ID appears twice except one fraud detection case.
  • Find the unique sensor reading anomaly when duplicate measurements are expected.
  • Detect a single non-repeating element in a data stream during ETL validation.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.