Find the Missing Number in an Array

Problem

An array contains n distinct numbers from the range 0 to n. Find the one number missing from the array.

Input:  nums = [3, 0, 1]
Output: 2

Python Solution

def missing_number(nums):
    n = len(nums)
    expected_sum = n * (n + 1) // 2
    return expected_sum - sum(nums)

C++ Solution

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;
}

Java Solution

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;
    }
}

Complexity

Time: O(n) — summing the array takes one pass. Space: O(1) — only the two sums are stored, using the closed-form sum formula instead of a hash set.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.