Skip to main content

5. Single Number

easyAsked at JetBrains

Find the one element that appears once when all others appear twice — JetBrains uses this to test XOR fluency, a primitive in their hash-based PSI fingerprints.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a non-empty array where every element appears twice except for one, find that single element. Solve in linear time without extra memory.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Exactly one element 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. Hash count

Count occurrences in a map, return the entry with count 1; needs O(n) extra space.

Time
O(n)
Space
O(n)
const m = new Map();
for (const n of nums) m.set(n,(m.get(n)||0)+1);
for (const [k,v] of m) if (v===1) return k;

Tradeoff:

2. XOR fold

XOR all elements; duplicate pairs cancel, leaving the singleton. Same idea as JetBrains's PSI fingerprint diffing where paired hashes cancel.

Time
O(n)
Space
O(1)
function singleNumber(nums) {
  let acc = 0;
  for (const n of nums) acc ^= n;
  return acc;
}

Tradeoff:

JetBrains-specific tips

JetBrains expects you to explain the XOR identity (a^a=0, a^0=a) cleanly — they care that you can reason about bitwise operations the same way their indexer composes file hashes.

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 JetBrains interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →