Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
Using math wikipedia to calculate the sum of the first consecutive integers:
class Solution: def missingNumber(self, nums: list[int]) -> int: length = len(nums) math_sum = (length * (length+1)) // 2 missing = math_sum - sum(nums) return missing
/** * @param {number[]} nums * @return {number} */ var missingNumber = function(nums) { // sum of array const sum_reducer = (accumulator, currentValue) => accumulator + currentValue; const array_sum = nums.reduce(sum_reducer) // expected sum = 0.5 * (length * (length+1)) const length = nums.length let consecutive_sum = 0.5 * (length * (length + 1)) consecutive_sum = Math.trunc(consecutive_sum) return consecutive_sum - array_sum };
Since we have to use reduce and loop over the array, it is also possible to substract each number from the sum instead.
There was an error while loading. Please reload this page.