InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Bit Manipulation

Single Number II

medium Original ↗ 00:00

Problem

You are given an integer array nums in which every element appears exactly three times, except for one element that appears exactly once. Return that single element.

You must do it in linear time and using only constant extra space — no hash map of counts, no extra array proportional to the input.

Examples

  • nums = [2, 2, 3, 2]3 2 appears three times; 3 is the lone element.
  • nums = [0, 1, 0, 1, 0, 1, 99]99 0 and 1 each appear three times; 99 appears once.
  • nums = [-2, -2, 1, 1, -2, 1, 5]5 Negatives are allowed; -2 and 1 each appear three times, 5 is alone.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1 (values can be negative; assume 32-bit integers).
  • Every element appears exactly three times except one, which appears exactly once — the input is guaranteed to have this shape.
  • Target complexity: O(n) time, O(1) space.

Think about it first

Hint 1 A frequency count (hash map, or a sum-of-unique trick) solves it in O(n) space. The constraint is O(1) space. Instead of treating each number as a whole value, consider one bit position at a time.
Hint 2 Look at a single bit position across the whole array. Every number that appears three times contributes that bit either 0 or 3 times. The lone number contributes it 0 or 1 more. So the total count of 1s at that position is `3k` or `3k + 1` — its value mod 3 reveals the lone number's bit.
Hint 3 Sum the 1-bits at each of the 32 positions, take each sum mod 3, and reassemble the answer: O(32n) = O(n) time, O(1) space. Watch the sign bit (position 31); a set bit there means the answer is negative. A two-variable "ones/twos" state machine does the same job in a single pass.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug