10. Single Number
easyAsked at RampFind the one element that appears exactly once when every other element appears twice.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a non-empty array of integers nums, every element appears twice except for one. Find that single element. Your algorithm should run in linear time and use only constant extra space.
Constraints
1 <= nums.length <= 3 * 10^4Each element appears twice except for one which appears once
Examples
Example 1
nums = [2,2,1]1Example 2
nums = [4,1,2,1,2]4Approaches
1. Brute force with map
Count occurrences in a hash map then scan for the count-of-one entry.
- Time
- O(n)
- Space
- O(n)
function singleNumber(nums) {
const counts = new Map();
for (const n of nums) counts.set(n, (counts.get(n) || 0) + 1);
for (const [n, c] of counts) if (c === 1) return n;
}Tradeoff:
2. XOR fold
XOR every element. Duplicates cancel (a ^ a = 0) leaving only the unique value.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let acc = 0;
for (const n of nums) acc ^= n;
return acc;
}Tradeoff:
Ramp-specific tips
Ramp uses XOR-style reconciliation when matching duplicate vendor records across their AP automation pipeline; the constant-space signal here is exactly the bonus they're grading.
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 Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →