Single Number (XOR)

Easy~10 min

Given a non-empty array of integers nums where every element appears exactly twice except for one element which appears exactly once, find and return that single element.

You must solve this using XOR bit manipulation with O(n) time and O(1) extra space.

Examples

Example 1
Input: nums = [2, 2, 1]
Output: 1
Explanation: 2 appears twice and 1 appears once. The single number is 1.
Example 2
Input: nums = [4, 1, 2, 1, 2]
Output: 4
Explanation: 1 and 2 each appear twice. 4 appears once.
Example 3
Input: nums = [1]
Output: 1
Explanation: Only one element, so it is the single number.

Constraints

  • 1 <= nums.length <= 10^4
  • nums.length is odd
  • -10^4 <= nums[i] <= 10^4
  • Every element appears exactly twice except one which appears once
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run