18. Single Number
easyAsked at OlaFind the lone element in an array where every other element appears twice.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a non-empty array of integers nums where every element appears twice except for one, find that single one. Your algorithm should have linear runtime complexity and use constant extra space.
Constraints
1 <= nums.length <= 3 * 10^4-3*10^4 <= nums[i] <= 3*10^4
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 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 all values; duplicates cancel and the lone value remains.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let acc = 0;
for (const x of nums) acc ^= x;
return acc;
}Tradeoff:
Ola-specific tips
Ola favors the XOR insight; mention how it removes the need for a dedup table when scanning paired pickup/drop-off event IDs.
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 Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →