147. Single Number
Every distinct value except one appears exactly twice. Identify the remaining value, which occurs once, while preserving the array.
The occurrence promise is part of the problem; this is not a general most-frequent or least-frequent query. Signed integer values must retain their exact bit representation.
Example 1
Input
nums=[2,2,1]
Output
1
Explanation: The equal pair cancels, leaving the singleton.
Example 2
Input
nums=[4,1,2,1,2]
Output
4
Explanation: Pairs need not be adjacent or sorted.
Example 3
Input
nums=[-2147483648,7,7]
Output
-2147483648
Explanation: The sign bit participates in XOR just like every other bit.
Constraints
1 <= nums.length <= 100001-231 <= nums[i] <= 231 - 1- The length is odd. Exactly one value occurs once; every other value occurs twice.
Hints
Hint 1
What binary operation makes a value cancel itself?
Hint 2
Can associativity and commutativity group nonadjacent equal occurrences conceptually?
Hint 3
Fold from zero with XOR, and explain why only the complete promised multiset has a singleton interpretation.
Submissions
Your recent submissions for this problem.
Checking sign-in…
Discussion
Ask a question or share an approach. Posts are public; avoid personal information and mark solution spoilers clearly.
No discussion yet. Start the conversation with a question about this problem.
Checking sign-in…
Run your code to check the sample cases, or submit it to check the full validation suite.
Nonadjacent pairs disappear only after all occurrences
[4,1,2,1,2]
4