[LeetCode] 268. Missing Number

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

Thought process:
Use the XOR operation. a ^ a = 0. Since the numbers run from 0 to n, nums[i] ^ i = 0. If there's no number missing, nums[0] ^ 0 ^ nums[1] ^ 1 ^ ... ^ nums[n] ^ n = 0. Now that there's one number missing, the result of the above XOR calculation will give me the missing number.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    public int missingNumber(int[] nums) {
        int i = 0;
        int xor = 0;
        
        for (; i < nums.length; i++) {
            xor ^= i ^ nums[i];
        }
        return xor ^ i;
    }
}

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

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula