Single Number
Single Number
Given a non-empty array of integers where every element appears exactly twice except for one element which appears exactly once, find and return that single element. Your solution must have O(n) time complexity and use O(1) extra space — no hash maps or sets. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=5, nums=[4 1 2 1 2] → 4
Input format — only if your code reads from stdin
Input format (stdin): - First line: integer n (array size, always odd) - Second line: n space-separated integers Output: the element that appears exactly once.
Approach
XOR trick: XOR of a number with itself is 0; XOR of any number with 0 is that number. XOR all elements together — pairs cancel out (a^a=0), leaving only the single element. Result = nums[0]^nums[1]^...^nums[n-1].
Input
Output
- •
1 ≤ n ≤ 3×10^4, n is always odd, -3×10^4 ≤ nums[i] ≤ 3×10^4
More Bit Manipulation problems
Browse all coding problems →Press Run to test your custom input, or Submit to judge against all test cases.
Sign in to continue
Create a free account to run code, submit solutions and track progress.
- Free forever — no credit card
- 10+ languages with live execution
- Points, streaks & leaderboards