11. Single Number
easyAsked at NubankFind the element that appears once when every other element appears twice; Nubank uses it to probe bit-tricks intuition before deeper credit-ledger reconciliation problems.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a non-empty array of integers nums in which every element appears twice except for one, return that single element. Solve it in linear time and constant extra space.
Constraints
1 <= nums.length <= 3 * 10^4Each element appears twice except one which appears once
Examples
Example 1
nums = [2,2,1]1Example 2
nums = [4,1,2,1,2]4Approaches
1. Hash count
Tally counts in a Map, return the one with count 1.
- Time
- O(n)
- Space
- O(n)
function singleNumber(nums){ const m=new Map(); for(const n of nums) m.set(n,(m.get(n)||0)+1); for(const [k,v] of m) if(v===1) return k; }Tradeoff:
2. XOR fold
XOR is associative, commutative, and self-inverse, so XOR-ing everything cancels the duplicates and leaves the loner. O(1) extra space.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let acc = 0;
for (const n of nums) acc ^= n;
return acc;
}Tradeoff:
Nubank-specific tips
Nubank likes the XOR answer — it shows you can reach for bitwise identities, useful when reconciling double-posted transaction events on PIX rails.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Single Number and other Nubank interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →