Skip to content
Problem 260 · LeetCode 260(opens in a new tab)

Single Number III

MediumArrays

You get an integer array nums. Exactly two of its values appear once each; every other value appears exactly twice. Return the two values that appear once, in either order.

Your solution should run in linear time and use only a constant amount of extra memory.

Example 1

Input:  nums = [7, 2, 7, 3]
Output: [2, 3]
Why:    7 shows up twice; 2 and 3 once each
2 more examples and the constraints

Example 2

Input:  nums = [-4, 9]
Output: [-4, 9]
Why:    both values appear once

Example 3

Input:  nums = [10, 3, 10, 0, 3, 5]
Output: [0, 5]
Why:    10 and 3 are paired; [5, 0] is also accepted

Constraints

  • 2 ≤ length of nums ≤ 30,000
  • −2^31 ≤ nums[i] ≤ 2^31 − 1
  • Exactly two values appear once; all others appear twice

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count with a hash mapO(n)
  2. XOR, then split by one bitO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30,000 numbersVerdict
Count with a hash mapO(n)
Simple; O(n) memory
XOR, then split by one bitO(n)
Best; O(1) memory

n = length of nums.

Edge cases to test

  • Only two numbers. [-4, 9] has no pairs; both are the answer.
  • Zero is a single. 0 has no set bits, so it always lands in the b group, and that still works.
  • Extreme values. −2^31 and 2^31 − 1 differ in every bit; xor is −1 and low is 1.
  • Negative numbers. XOR works on the two's complement bits, so signs need no special care.

Common mistakes

  • Returning xor itself, which is a ^ b, not either single.
  • Splitting on a bit that is clear in xor: then a and b land in the same group.
  • Writing x & low == 0 in Java or C++, where == binds tighter than &.

How to talk through it

  1. 1Clarify. Exactly two singles, everything else exactly twice? Any order for the answer?
  2. 2Give the map. Counting works in O(n) time but uses O(n) memory.
  3. 3Use XOR. XOR of all numbers is a ^ b because pairs cancel.
  4. 4Split by one bit. A set bit of a ^ b separates a from b and keeps each pair together.
  5. 5Test out loud. Try two numbers only, a zero single, and −2^31 with 2^31 − 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?