268. Missing Number
Asked at 16Bloomberg54Amazon54Microsoft49Google46Meta43Apple35tcs50Arista Networks84Revolut68HCL60Nvidia55Zoho42Salesforce41Infosys39IBM35Goldman Sachs21
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
assert Solution().missingNumber([3, 0, 1]) == 2
assert Solution().missingNumber([9, 6, 4, 2, 3, 5, 7, 0, 1]) == 8
class Solution {
public int missingNumber(int[] nums) {
int x = nums.length;
for (int i = 0; i < nums.length; i++) x ^= i ^ nums[i];
return x;
}
}
func missingNumber(nums []int) int {
x := len(nums)
for i, v := range nums { // xor all indices 0..n and all values: only the missing one survives
x ^= i ^ v
}
return x
}