268. Missing Number
🟩 Easy
Question
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
Note: If array is sorted, then the binary search will be the optimal for searching.
Example 1:
Example 2:
Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
Hash Set Approach
Time complexity: O(n)
Space complexity: O(n)
Bi Manipulation
Because we know that nums
contains nn numbers and that it is missing exactly one number on the range [0..n-1][0..n−1], we know that nn definitely replaces the missing number in nums
. Therefore, if we initialize an integer to nn and XOR it with every index and value, we will be left with the missing number. Consider the following example (the values have been sorted for intuitive convenience, but need not be):
Index
0
1
2
3
Value
0
1
3
4
Time complexity: O(n)
Space complexity: O(1)
Partial Sums Approach
Time complexity: O(n)
Space complexity: O(1)
Last updated
Was this helpful?