SDE & MLE Prep

268. Missing Number

Problem

nums contains n distinct numbers from the range [0, n], so exactly one is missing. Return it.

Example: [3,0,1] → 2; [9,6,4,2,3,5,7,0,1] → 8

Constraints: follow-up: O(1) extra space and O(n) time.

XOR all indices 0..n with all values; everything pairs up except the missing number. (Or n(n+1)/2 − sum.)

Complexity: O(n) time, O(1) space.

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        x = len(nums)
        for i, v in enumerate(nums):
            x ^= i ^ v
        return x