Skip to content

268. Missing Number

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int missingNumber(vector<int>& nums) {
    int ans = nums.size();

    for (int i = 0; i < nums.size(); ++i)
      ans ^= i ^ nums[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
  public int missingNumber(int[] nums) {
    int ans = nums.length;

    for (int i = 0; i < nums.length; ++i)
      ans ^= i ^ nums[i];

    return ans;
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def missingNumber(self, nums: list[int]) -> int:
    ans = len(nums)

    for i, num in enumerate(nums):
      ans ^= i ^ num

    return ans