Math and Logic: Missing Number

Given an array nums containing \(n\) integers in the range \([0, n]\) without any duplicates, return the single number in the range that is missing from nums.

Answer

We calculate the difference between the theoretical sum \(\frac{n(n+1)}{2}\) and the actual sum of the array to find the missing number.

Python
return sum_total - sum_actual

Time complexity: \(O(n)\).

Programming lessons learned:

  • The operator // returns an integer (floor division), while / returns a float.

  • The function sum(nums) is used to calculate the total of all elements in a list.

Back to collection