18. Single Number
easyAsked at LyftFind the element that appears once when every other element 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. Solve it with linear runtime and constant space.
Constraints
1 <= nums.length <= 3*10^4Each element except one appears twice
Examples
Example 1
nums = [2,2,1]1Example 2
nums = [4,1,2,1,2]4Approaches
1. Hash map count
Count occurrences and 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 all
XOR is its own inverse, so pairs cancel and only the singleton remains.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let r = 0;
for (const x of nums) r ^= x;
return r;
}Tradeoff:
Lyft-specific tips
Lyft engineers cite XOR tricks in deduplicating event logs from rides; they'll ask you to prove why it works using XOR's associativity and self-inverse property.
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 Lyft interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →