Skip to content
Problem 137 · LeetCode 137(opens in a new tab)

Single Number II

MediumArrays

You are given an integer array nums. Every value in it appears exactly three times, except for one value that appears only once. Return that one value.

Your solution should run in linear time and use only a constant amount of extra memory.

Example 1

Input:  nums = [6, 3, 6, 6]
Output: 3
Why:    6 shows up three times, 3 only once
2 more examples and the constraints

Example 2

Input:  nums = [8, -5, 8, 1, -5, 8, -5]
Output: 1
Why:    8 and −5 appear three times each

Example 3

Input:  nums = [42]
Output: 42
Why:    a list of one holds only the single value

Constraints

  • 1 ≤ nums.length ≤ 30,000
  • −2³¹ ≤ nums[i] ≤ 2³¹ − 1
  • Exactly one value appears once; every other value appears three times

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count with a hash mapO(n)
  2. Count each bit positionO(32·n)
  3. Two masks: ones and twosO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 30,000 numbersVerdict
Count with a hash mapO(n)
Fast, but O(n) memory
Count each bit positionO(32·n)
Meets both limits
Two masks: ones and twosO(n)
Best; one pass, two integers

n = how many numbers are in the list; 32 is the number of bits in an integer.

Edge cases to test

  • Only one number. [42] has no triples, so the answer is 42.
  • The single number is 0. [9, 0, 9, 9]: every bit count is a multiple of 3, so the answer is 0.
  • Negative values. [7, −4, 7, 7] gives −4; its sign bit is left over like any other bit.
  • Values at the int limits. With −2³¹ three times and 2³¹ − 1 once, every bit but the sign bit is left over: the answer is 2³¹ − 1.

Common mistakes

  • Using XOR of everything as in Single Number: three copies XOR to the value itself, not to 0.
  • In Python, returning the bit-count result without fixing the sign, so −4 comes back as 4,294,967,292.
  • Updating twos with the old ones (or swapping the two lines), which breaks the 0 → 1 → 2 → 0 cycle.

How to talk through it

  1. 1Clarify. Does every other value appear exactly three times? Can values be negative or at the 32-bit limits?
  2. 2Give the simple answer. A count map finds it in O(n) time, but uses O(n) memory, which the question rules out.
  3. 3Think in bits. In each bit column, the triples add a multiple of 3. Count each column mod 3 and the leftovers are the answer.
  4. 4Compress the counts. Keep all 32 counters at once in two masks, ones and twos, updated in one pass. O(n) time, O(1) space.
  5. 5Test out loud. Run a one-element list, a case where the answer is 0, and a negative answer.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?