12. Single Number
easyAsked at MercadoLibreFind the integer that appears exactly once when every other appears twice.
By Alex Chen, 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. Your solution should run in linear time and use constant extra space.
Constraints
1 <= nums.length <= 3 * 10^4Each element appears twice except one
Examples
Example 1
nums = [2,2,1]1Example 2
nums = [4,1,2,1,2]4Approaches
1. Hash count
Count occurrences in a map and return the entry with count 1.
- Time
- O(n)
- Space
- O(n)
const c = new Map();
for (const n of nums) c.set(n, (c.get(n) || 0) + 1);
for (const [k, v] of c) if (v === 1) return k;Tradeoff:
2. XOR fold
XOR all elements; duplicates cancel and the lone element remains.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let x = 0;
for (const n of nums) x ^= n;
return x;
}Tradeoff:
MercadoLibre-specific tips
MercadoLibre fraud teams love the XOR trick because it mirrors signature reconciliation — paired chargeback events cancel and the unmatched dispute pops out the same way.
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 MercadoLibre interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →