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.
- Count with a hash mapO(n)
- 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
| Approach | Time | Relative work for 30,000 numbers | Verdict |
|---|---|---|---|
| Count with a hash map | O(n) | Simple; O(n) memory | |
| XOR, then split by one bit | O(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
bgroup, and that still works. - Extreme values. −2^31 and 2^31 − 1 differ in every bit;
xoris −1 andlowis 1. - Negative numbers. XOR works on the two's complement bits, so signs need no special care.
Common mistakes
- Returning
xoritself, which isa ^ b, not either single. - Splitting on a bit that is clear in
xor: thenaandbland in the same group. - Writing
x & low == 0in Java or C++, where==binds tighter than&.
How to talk through it
- 1Clarify. Exactly two singles, everything else exactly twice? Any order for the answer?
- 2Give the map. Counting works in O(n) time but uses O(n) memory.
- 3Use XOR. XOR of all numbers is
a ^ bbecause pairs cancel. - 4Split by one bit. A set bit of
a ^ bseparatesafromband keeps each pair together. - 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?