Skip to main content

3. Single Number

easyAsked at Redis

Find the one element that appears once when every other appears twice; Redis uses it to probe XOR-trick fluency relevant to bitmap operations.

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 element. Solve in linear time and constant space.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • Each element appears twice except one

Examples

Example 1

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

Example 2

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

Approaches

1. Hash map count

Count occurrences then scan.

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 numbers; duplicates cancel and only the single survives. This is the same bit trick Redis uses inside BITCOUNT and BITOP XOR.

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

Tradeoff:

Redis-specific tips

Redis values the XOR-fold insight because the same algebra powers BITOP XOR over Redis bitmaps; mention BITCOUNT when discussing space-efficient set membership.

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

Practice these live with InterviewChamp.AI →