LeetCode Solutions

268. Missing Number

Time: $O(n)$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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

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

    return ans