Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Find Missing Number in Sequence

Find one missing value from one through n using sums. Students trace the triangular-number formula and see the exact input assumptions behind subtraction.

AdvancedPhase 4 - Level 5: Logical & AppliedExample 13 of 14
find-missing-number-in-sequence.py
1# Take array
2n = int(input("Enter n (expected range 1 to n): "))
3arr = []
4for i in range(n - 1):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Calculate expected sum
8expected_sum = n * (n + 1) // 2
9actual_sum = sum(arr)
10missing = expected_sum - actual_sum
11
12print(f"Missing number: {missing}")

Output

Enter n (expected range 1 to n): 5
Element 1: 1
Element 2: 2
Element 3: 4
Element 4: 5
Missing number: 3

In this one

  • Use an expected-sum identity
  • Require exactly one omission
  • Recognize unvalidated assumptions

How it works

  1. 1

    Read n - 1 expected-range values.

  2. 2

    Calculate n * (n + 1) // 2.

  3. 3

    Subtract the actual total to obtain the missing value.

Edge cases

Can duplicates invalidate the result?

Can duplicates invalidate the result?

Yes. The sum alone does not validate the input set.

What happens for n = 1?

What happens for n = 1?

No values are read and the missing value is one.

What's going on

The expected total is n * (n + 1) // 2. The collected n - 1 values should contain every number from one through n except one.

Subtracting their actual total reveals that missing value. This relies on valid range values with no repeats; arbitrary input can produce a misleading result. Integer division is exact here because the product of consecutive integers is even.

Can duplicates invalidate the result? Yes. The sum alone does not validate the input set.

What happens for n = 1? No values are read and the missing value is one.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why use n - 1 inputs?

Pick an answer to check it.

Question 2

Can duplicates invalidate the result?

Pick an answer to check it.

Questions people ask

Can duplicates invalidate the result?

Yes. The sum alone does not validate the input set.

What happens for n = 1?

No values are read and the missing value is one.

Why use n - 1 inputs?

Exactly one of the n expected values is absent.