Find Missing Numbers, Duplicates, and Ranges in Python
Analyze a list to identify missing numbers, duplicate values, and contiguous ranges using sets and the Counter class.
Python code
37 linesdef find_missing_duplicates_ranges(numbers):
"""Find missing numbers, duplicates, and ranges in a list."""
from collections import Counter
if not numbers:
return {"missing": [], "duplicates": [], "ranges": []}
full_range = set(range(min(numbers), max(numbers) + 1))
present = set(numbers)
missing = sorted(full_range - present)
duplicates = sorted([num for num, count in Counter(numbers).items() if count > 1])
ranges = []
if numbers:
sorted_nums = sorted(numbers)
start = prev = sorted_nums[0]
for num in sorted_nums[1:]:
if num == prev + 1:
prev = num
else:
ranges.append((start, prev) if start != prev else (start,))
start = prev = num
ranges.append((start, prev) if start != prev else (start,))
return {"missing": missing, "duplicates": duplicates, "ranges": ranges}
if __name__ == "__main__":
example = [1, 1, 2, 4, 5, 5, 6, 9, 9]
result = find_missing_duplicates_ranges(example)
print(f"Input: {example}")
print(f"Missing numbers: {result['missing']}")
print(f"Duplicates: {result['duplicates']}")
print(f"Ranges: {result['ranges']}")
Output
Input: [1, 1, 2, 4, 5, 5, 6, 9, 9]
Missing numbers: [3, 7, 8]
Duplicates: [1, 5, 9]
Ranges: [(1, 2), (4, 6), (9,)]
How it works
This function uses sets to compute missing numbers efficiently by subtracting the present set from the full range of values. The Counter class from collections counts occurrences to identify duplicates. For ranges, the code sorts the inputs and tracks consecutive sequences, appending either a tuple of two numbers for a range or a single-element tuple for isolated values. The empty input is handled early with a clear return statement. Time complexity is O(n log n) due to sorting, which is acceptable for most practical lists.
Common mistakes
- Forgetting to handle the empty list case before accessing min() or max()
- Assuming duplicates are unique without using Counter correctly
- Building ranges on unsorted data, which produces incorrect consecutive groupings
Variations
- Use a dictionary comprehension instead of Counter for counting: {num: numbers.count(num) for num in set(numbers)}
- Return ranges as strings like '1-2, 4-6, 9' for prettier display output
Real-world use cases
- Auditing a sequence of invoice numbers to identify gaps and repeated entries before processing payments.
- Checking log file line numbers to find skipped records and duplicate writes during data import jobs.
- Validating seat assignments in a booking system to find unoccupied and double-booked seats in a row.
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.