Skip to main content

10. Single Number

easyAsked at Ramp

Find 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^4
  • Each element appears twice except for one which appears once

Examples

Example 1

Input
nums = [2,2,1]
Output
1

Example 2

Input
nums = [4,1,2,1,2]
Output
4

Approaches

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.

Output

Press Run or Cmd+Enter to execute

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 →