18. Single Number
easyAsked at BoxFind the only element appearing once in an array where every other appears twice — Box uses XOR-style tricks when matching unpaired sync events to detect orphans.
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 one. Must be linear time 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 counter
Count occurrences; return the key with count 1.
- Time
- O(n)
- Space
- O(n)
const c = new Map();
for (const x of nums) c.set(x, (c.get(x)||0)+1);
for (const [k,v] of c) if (v === 1) return k;Tradeoff:
2. XOR fold
XOR all elements; pairs cancel, leaving the unique one. O(1) space.
- Time
- O(n)
- Space
- O(1)
function singleNumber(nums) {
let r = 0;
for (const x of nums) r ^= x;
return r;
}Tradeoff:
Box-specific tips
Box loves XOR-fold answers — they map it to fingerprinting unpaired sync events without allocating per-event counters.
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 Box interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →