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.
Python code
13 linesfrom 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
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
- Use XOR bitwise operation to find the single number in O(n) time and O(1) space.
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.