↓Skip to main content
  1. LeetCode/

LeetCode 268: Missing Number

·1 min· ·
LeetCode Easy Array Hash-Table Math Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-23

  • Submissions: Accepted → Wrong Answer → Accepted

Approach
#

0..n has n + 1 numbers and the array is missing one. The full sum is n(n + 1) / 2; subtracting the array’s sum gives the missing value. XOR also works: XOR all of 0..n with the array, pairs cancel, and the missing one remains.

My Attempts
#

The first submission passed. A November rewrite sorted and looked only for gaps larger than 1, missing the case where 0 is absent: [1] should be 0; it returned 1.

Solution
#

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        return n * (n + 1) // 2 - sum(nums)

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • The missing value may be 0 or n; checking only gaps after sorting misses both.

Interview Explanation
#

The sum of 0..n is n(n+1)/2; subtracting the array’s sum gives the missing number. Time O(n), space O(1).

Related

LeetCode 349: Intersection of Two Arrays
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 349 note: convert both arrays to sets and intersect them
LeetCode 350: Intersection of Two Arrays II
·1 min
LeetCode Easy Array Hash-Table Two-Pointers Binary-Search
LeetCode 350 note: an intersection keeping multiplicity, where Counter’s & takes the smaller count from each side
LeetCode 367: Valid Perfect Square
·1 min
LeetCode Easy Math Binary-Search
LeetCode 367 note: binary search [1, num] for mid² == num without using sqrt
LeetCode 202: Happy Number
·1 min
LeetCode Easy Hash-Table Math Two-Pointers Floyds-Cycle-Finding-Algorithm
LeetCode 202 note: repeatedly take the sum of squared digits, which reaches 1 or enters a cycle; detect it with a set of seen numbers or fast and slow pointers
LeetCode 217: Contains Duplicate
·1 min
LeetCode Easy Array Hash-Table Sorting
LeetCode 217 note: if converting to a set shortens the array, there is a duplicate
LeetCode 219: Contains Duplicate II
·2 mins
LeetCode Easy Array Hash-Table Sliding-Window
LeetCode 219 note: a hash map stores each value’s last index; only the most recent occurrence needs a distance check