Single Number II

Solve this Problem
Medium20–25 min
Topics
Companies
Practice:GFG ↗
This time the pattern is triples, not pairs — every value in the array repeats exactly three times except for one lone holdout that shows up just once. Identify it. Plain XOR can't help here, since XOR-ing a value with itself three times just leaves the value unchanged (it doesn't cancel like it does for pairs). Instead, look at each of the 32 bit positions on its own: a value repeated three times always contributes a multiple of 3 to that position's total, so any position whose total isn't a multiple of 3 must be getting its extra contribution from the one unpaired value.

Test Case 1:

Input:nums = [2, 2, 3, 2]
Output:3
Explanation:2 shows up three times; 3 is the lone value.

Test Case 2:

Input:nums = [0, 1, 0, 1, 0, 1, 99]
Output:99
Explanation:0 and 1 each appear three times; 99 stands alone.

Test Case 3:

Input:nums = [5, 5, 5, 7]
Output:7
Explanation:One triple and one single value.

Constraints

  • 1 ≤ nums.length ≤ 3 × 10⁴
  • -3 × 10⁴ ≤ nums[i] ≤ 3 × 10⁴
  • Every value in nums appears exactly three times, except for one value which appears exactly once
🚀

Try the Dry Run

Don't just read the solution — watch it execute, one step at a time.

Approach & Solutions

Hashmap Counting

Good

Count how many times each value occurs, then scan for the one entry whose count is 1. This works regardless of whether the repeated values show up twice, three times, or any other fixed count — but it always costs memory proportional to how many distinct values are in the array.

TimeO(n)
SpaceO(n)
1class Solution { 2 public int singleNumber(int[] nums) { 3 Map<Integer, Integer> freq = new HashMap<>(); 4 for (int num : nums) { 5 freq.put(num, freq.getOrDefault(num, 0) + 1); 6 } 7 for (Map.Entry<Integer, Integer> entry : freq.entrySet()) { 8 if (entry.getValue() == 1) { 9 return entry.getKey(); 10 } 11 } 12 return -1; 13 } 14}

Optimal — Bit Position Counting

Optimal

Look at each of the 32 bit positions independently. For every position, add up how many numbers have a 1 there. Since every repeated value contributes that bit exactly three times (or zero times), the total at each position is always a multiple of 3 — except at positions where the single value has a 1 bit, which tips the total to one more than a multiple of 3. Whichever bit positions have a count not divisible by 3 belong to the answer.

TimeO(n)
SpaceO(1)
1class Solution { 2 public int singleNumber(int[] nums) { 3 int result = 0; 4 for (int bit = 0; bit < 32; bit++) { 5 int count = 0; 6 for (int num : nums) { 7 if (((num >> bit) & 1) != 0) { 8 count++; 9 } 10 } 11 if (count % 3 != 0) { 12 result |= (1 << bit); 13 } 14 } 15 return result; 16 } 17}

Related Problems