Skip to content

136. Single Number 👍

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

    for (const int num : nums)
      ans ^= num;

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

    for (final int num : nums)
      ans ^= num;

    return ans;
  }
}
1
2
3
class Solution:
  def singleNumber(self, nums: List[int]) -> int:
    return functools.reduce(operator.xor, nums, 0)