my dsa gallery
ArrayBit Manipulation / Math

Missing Number

Problem link: https://leetcode.com/problems/missing-number/

Problem Statement

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.

Input

An array of n distinct integers in the range [0, n].

Output

The single missing integer.

Example

Input: nums = [3,0,1] Output: 2 Explanation: n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range.

Explanation

The array has a length of 3, meaning the numbers should be 0, 1, 2, 3. Comparing the sum of the expected range to the actual sum reveals the missing value.

Brute Force

Intuition

Sort the array first. After sorting, the number at each index should match the index itself (nums[i] == i). The first index where this fails is the missing number.

Approach

  1. Sort the input array nums.
  2. Iterate through the array from i = 0 to n-1.
  3. If nums[i] != i, return i.
  4. If the loop completes, the missing number is n.

Dry Run

nums = [3,0,1] Sorted: [0,1,3] i=0: 0 == 0 (OK) i=1: 1 == 1 (OK) i=2: 3 != 2 (Found! Return 2)

Code (Java)

Time: O(N log N)Space: O(1)

Complexity Analysis

Sorting the array takes O(N log N) time.

Optimal Solution

Intuition

Mathematical Approach: Use the formula for the sum of the first n natural numbers. Subtract the actual sum of the array from this expected sum to find the missing number.

Approach

  1. Calculate n (length of nums).
  2. Calculate expectedSum = n * (n + 1) / 2.
  3. Calculate actualSum by adding all elements in nums.
  4. Return expectedSum - actualSum.
Step 1 of 2- Math Formula
Sum of 1 to N
Loading...
Use arrow keys to navigate

Dry Run

nums = [3,0,1], n = 3 Expected: 3 * (4) / 2 = 6 Actual: 3 + 0 + 1 = 4 Missing: 6 - 4 = 2

Code (Java)

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;
    }
}
Time: O(N)Space: O(1)

Complexity Analysis

We iterate through the array once to calculate the actual sum.

Quick Revision (Brute Force)

  • Sort and compare with index
  • O(N log N) time

Quick Revision (Optimal)

  • Math: Expected Sum - Actual Sum
  • XOR: XOR all indices and values
  • O(N) time, O(1) space

Study Photos

Upload screenshots/notes for this specific problem.

Drag & drop or click to select
Drop an image anywhere in this box to upload.
No photos uploaded till now.

Comments

Stored in D1. Login required.
No comments yet.