MissingNumber
Problem
Solution
Let \(m \in \{1, ..., n\}\) be the missing number. Since nums
\(= \{1, ..., n\} - \{m\}\),
\[\begin{split}\begin{align}
\DeclareMathOperator{\sumof}{sumof}
\sumof(nums) &= \left( \sum_{i=1}^{n} i \right) - m \\
m &= \sum_{i=1}^{n} i - \sumof(nums)
\end{align}\end{split}\]
Use the formula
\[\sum_{i=1}^{n} i = \frac{n(n+1)}{2}\]
to calculate the the sum
from 1 to \(n\) quickly. Note that \(n\) is one more than the number of
elements in nums
.
Code
https://github.com/GeorgeRPu/tech-interview-prep/blob/main/solutions/MissingNumber.py
from typing import List
def missingNumber(nums: List[int]) -> int:
"""Find the single missing number in a list of integers.
"""
n = len(nums)
s = sum(nums)
return n * (n + 1) // 2 - s
Test
>>> from MissingNumber import missingNumber
>>> list1 = list(range(4))
>>> list1.remove(2)
>>> missingNumber(list1)
2
>>> list2 = list(range(100))
>>> list2.remove(47)
>>> missingNumber(list2)
47
Functions
|
Find the single missing number in a list of integers. |