You are given a non-empty list of whole numbers, nums. Every value in it shows up exactly two times, except for one value that shows up only once.
Return that lonely value. The challenge is to do it in a single linear pass while using only a fixed amount of extra memory, no matter how long the list is.
Example 1
Input: nums = [7, 3, 5, 3, 7] Output: 5 Why: 7 and 3 each have a twin; 5 does not
2 more examples and the constraints
Example 2
Input: nums = [9, 9, 4] Output: 4 Why: the two 9s pair up, leaving 4
Example 3
Input: nums = [-8] Output: -8 Why: a list of one has nothing to pair with
Constraints
- 1 ≤ length of nums ≤ 30,000
- Every number is between −30,000 and 30,000
- Exactly one value occurs once; every other value occurs exactly twice
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- Count with a hash mapO(n)
- XOR everythingO(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 |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| Count with a hash map | O(n) | Fast, but O(n) memory | |
| XOR everything | O(n) | Best; one pass, no memory |
n = how many numbers are in the list.
Edge cases to test
- Only one number. [-8] has nothing to cancel, so the answer is −8.
- Negative numbers. [-5, 2, -5] gives 2; the two −5s cancel like any pair.
- Zero is the single one. [0, 4, 4] gives 0. Starting result at 0 does not hide it.
- Single number first. [6, 1, 1]: order does not matter to XOR.
Common mistakes
- Sorting first and calling it linear: sorting is O(n log n).
- Starting the XOR at nums[0] and then XOR-ing nums[0] again, which cancels it.
- Reaching for a hash map when the question asks for O(1) extra space.
How to talk through it
- 1Clarify. Does every other value occur exactly twice, never three times? Can numbers be negative?
- 2Give the brute force. Check each number against all others; O(n²) time, O(1) space.
- 3Trade memory for time. A count map gets O(n) time but uses O(n) space, which the question rules out.
- 4Use XOR. Say the two rules, x ^ x = 0 and x ^ 0 = x, and that order does not matter. Pairs vanish.
- 5Test out loud. Run a single-element list and a case where the answer is 0 or negative.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?