Sum Formula
Intuition
The sum of all integers from 0 to n is n * (n + 1) / 2. If one number is missing from the array, the difference between this expected sum and the actual sum of the array elements gives us the missing number. This is a clean mathematical approach that avoids any extra data structures.
Algorithm
- Compute `n` as the length of the array.
- Calculate the expected sum: `n * (n + 1) / 2`.
- Calculate the actual sum of all elements in the array.
- Return `expectedSum - actualSum`.
O(n)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : nums) {
actualSum += num;
}
return expectedSum - actualSum;
}
};class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : nums) {
actualSum += num;
}
return expectedSum - actualSum;
}
}from typing import List
class Solution:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sumfunc missingNumber(nums []int) int {
n := len(nums)
expectedSum := n * (n + 1) / 2
actualSum := 0
for _, num := range nums {
actualSum += num
}
return expectedSum - actualSum
}