8. Single Number
easyAsked at WiseFind the one unpaired transaction in a stream where every other entry has a matching counter-entry — a tiny model of ledger reconciliation at Wise.
By Sam K., Founder, InterviewChamp.AI · Last verified
Problem
Given a non-empty array of integers where every element appears twice except for one, find that single one. Solve in linear time and constant extra space.
Constraints
1 <= nums.length <= 3 * 10^4Every element appears twice except oneO(1) extra space required
Examples
Example 1
nums=[2,2,1]1Example 2
nums=[4,1,2,1,2]4Approaches
1. Hash map count
Tally each integer, return the one with count 1.
- Time
- O(n)
- Space
- O(n)
const m=new Map();
for (const x of nums) m.set(x,(m.get(x)||0)+1);
for (const [k,v] of m) if (v===1) return k;Tradeoff:
2. XOR fold
XOR is its own inverse, so paired entries cancel and the lone entry survives. Constant space and one pass.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums){
let acc = 0;
for (const n of nums) acc ^= n;
return acc;
}Tradeoff:
Wise-specific tips
Wise interviewers love this XOR insight because ledger reconciliation is exactly the production analogue — paired debit/credit entries cancel and the unmatched leg is the bug.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
More Wise coding interview questions
- 1. Two Sum
- 2. Valid Parentheses
- 3. Merge Two Sorted Lists
- 4. Remove Duplicates from Sorted Array
- 5. Remove Element
- 6. Search Insert Position
- 7. Plus One
- 9. Linked List Cycle