Missing Number

How to Find the Missing Number in an Array

Finding a missing number in an array is a classic coding problem that tests your understanding of mathematical patterns and algorithm optimization. In this article, we’ll explore how to solve this problem efficiently, ensuring we meet the constraints of O(n) runtime and O(1) extra space complexity.

Pair with given sum - Two Sum

Problem Statement

You are given an array nums containing n integers, where the integers are in the range [0, n] and appear exactly once, except for one missing number. Your task is to identify the missing number.

Constraints

  • The length of the array satisfies: 1≤nums.length≤10001 \leq \text{nums.length} \leq 1000
  • All numbers in the array are distinct and within the range [0, n].
  • The solution should achieve:
    • O(n) runtime.
    • O(1) extra space.

Explanation:
Explanation:
The range [0, 3] contains the numbers {0, 1, 2, 3}. The number 0 is missing from the array nums.

Explanation:
The range [0, 2] includes the numbers {0, 1, 2}. The number 1 is missing.

There are mainly 4 approach to solve this problem – 

  1. Sorting
  2. Hash Set 
  3. Bitwise XOR
  4. Math

1. Sorting 

  • Time complexity: O(nlog⁡n)
  • Space complexityO(1) or O(n) depending on the sorting algorithm.

2. Hash Set 

Time & Space Complexity
    • Time complexity: O(n)
    • Space complexity: O(n)

Code

3. Bitwise XOR

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

4. Math

Time & Space Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles