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.

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

Python code

37 lines
Python 3.9+
def 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

stdout
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

  1. Use a dictionary comprehension instead of Counter for counting: {num: numbers.count(num) for num in set(numbers)}
  2. 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

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.