Skip to main content

6. Single Number

easyAsked at Byju's

Find the lone integer in an array where every other number 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 one. You must implement a solution with linear runtime complexity and use only constant extra space.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • Each element appears twice except for 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 set count

Count frequencies in a Map and return the one with count 1.

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 every value into an accumulator. Pairs cancel to zero so the lone value remains.

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

Tradeoff:

Byju's-specific tips

Byju's loves bit-trick problems for K-12 olympiad-style recruiting, so explain XOR cancellation in plain words a tenth-grader could follow.

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

Practice these live with InterviewChamp.AI →