Find Missing Number in Python Sequence 1 to N

Find the missing number from a list containing numbers 1 to N using the arithmetic sum formula.

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

Python code

11 lines
Python 3.9+
def find_missing_number(nums, n):
    expected_sum = n * (n + 1) // 2
    actual_sum = sum(nums)
    return expected_sum - actual_sum


if __name__ == "__main__":
    n = 10
    numbers = [1, 2, 3, 4, 5, 6, 7, 9, 10]
    missing = find_missing_number(numbers, n)
    print(f"The missing number is: {missing}")

Output

stdout
The missing number is: 8

How it works

The code computes the expected sum of all integers from 1 to n using the formula n*(n+1)//2, then subtracts the actual sum of the provided numbers. The difference equals the missing number because the formula sums the complete range while the list is missing exactly one element. This works in O(n) time and O(1) extra space, making it efficient for large n. The integer division // ensures the result is an integer even if n is odd.

Common mistakes

  • Off-by-one errors when computing the expected sum, using n*(n-1)//2 instead
  • Assuming the list is sorted or starts from 0 instead of 1
  • Forgetting that the function expects n and the list may be shorter by exactly one element

Variations

  1. Use XOR operation: xor all numbers from 1 to n and all elements in list, the result is the missing number
  2. Sort the list and scan for the gap if the list is unsorted and you need the missing element without arithmetic

Real-world use cases

  • Validating a batch of sequential IDs in a database to detect a skipped record.
  • Checking that a series of event sequence numbers in a log file has no gaps.
  • Verifying that a complete set of items (e.g., puzzle pieces or tickets) is present with one missing.

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.