Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Single Number

Bit Manipulationeasy

Every element in `nums` appears twice except one. Implement `singleNumber(nums)` returning the element that appears once, using XOR.

Sample tests

Input: singleNumber([2,2,1])
Output: 1
Input: singleNumber([4,1,2,1,2])
Output: 4

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Using a hash set works but uses extra space; XOR is O(1) space.

Learning resources

  • MDN: Bitwise operators
Approach & explanation (try first)

XOR of all elements leaves the unique value, in O(n) time and O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.