LeetCode 268: Missing Number — Step-by-Step Visual Trace


Easy — Array | Bit Manipulation | Math

The Problem

Given an array nums containing n distinct numbers in the range [0, n], find the one number that is missing from this range.

Approach

Use XOR properties where a ^ a = 0 and a ^ 0 = a. Initialize with n, then XOR with all indices and array elements - the missing number will remain after all pairs cancel out.

Time: O(n) · Space: O(1)

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        missing_num = n

        for i in range(n):
            missing_num ^= i ^ nums[i]

        return missing_num

Watch It Run

Try it yourself: Open TraceLit and step through every line.


Built with TraceLit — the visual algorithm tracer for LeetCode practice.


Comments