The "Missing Number" problem on Leetcode asks you to find the one number that is missing from an array containing n
distinct numbers taken from the range 0
to n
. The input is an array called nums
with n
elements, but the numbers are shuffled and one number in the range is missing. You must return the missing number.
0
to n
appears exactly once, except for the missing number.
Example: If nums = [3, 0, 1]
, then n = 3
, and the numbers in the range are 0, 1, 2, 3
. The missing number is 2
.
To solve this problem, we first think about a brute-force way: for each number between 0
and n
, check if it's in the array. This is simple but inefficient, as checking each value in the array can take a long time for large arrays.
Next, we look for patterns or mathematical properties. Since the numbers are supposed to be a complete sequence from 0
to n
with one missing, we can use formulas or clever data structures to find the missing value more efficiently.
We also consider whether we can use extra memory, or if we can solve it in-place. For this problem, we can aim for a solution that is both fast and uses minimal extra space.
There are several ways to solve this problem efficiently. Here are two popular methods:
n*(n+1)/2
.
nums
and subtract that from the expected sum, we get the missing number.
nums
.
Both methods run in linear time and use constant extra space. We'll use the summation formula for clarity.
nums
.
Example Input: nums = [3, 0, 1]
n = 3
.n * (n + 1) / 2 = 3 * 4 / 2 = 6
.3 + 0 + 1 = 4
.6 - 4 = 2
.
Thus, the missing number is 2
.
Brute-force Approach:
nums
(using a loop).The "Missing Number" problem is efficiently solved by leveraging mathematical properties of sequences. By comparing the expected sum (or using XOR), we can find the missing value in linear time and constant space. This approach is elegant because it avoids extra data structures and relies on simple arithmetic, making the code both fast and easy to understand.
class Solution:
def missingNumber(self, nums):
n = len(nums)
expected_sum = n * (n + 1) // 2
actual_sum = sum(nums)
return expected_sum - actual_sum
class Solution {
public:
int missingNumber(vector<int>& nums) {
int n = nums.size();
int expected_sum = n * (n + 1) / 2;
int actual_sum = 0;
for (int num : nums) {
actual_sum += num;
}
return expected_sum - actual_sum;
}
};
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;
}
}
var missingNumber = function(nums) {
const n = nums.length;
const expectedSum = n * (n + 1) / 2;
const actualSum = nums.reduce((a, b) => a + b, 0);
return expectedSum - actualSum;
};