Knowledge Guide
HomeDSACompany Practice

medium Single Number II

Problem Statement

Given an array of integers nums where each element appears three times, and one element appears exactly once, return the single element.

Note: You must solve the problem with linear runtime complexity and use only constant extra space.

Examples

Try it yourself

Try solving this question here:

✅ Solution Single Number II

Problem Statement

Given an array of integers nums where each element appears three times, and one element appears exactly once, return the single element.

Note: You must solve the problem with linear runtime complexity and use only constant extra space.

Examples

  • Example 1:
    • Input: nums = [4, 3, 3, 3]
    • Expected Output: 4
    • Justification: 4 is the only number that appears once, while 3 appears three times.
  • Example 2:
    • Input: nums = [99, 1, 99, 99, 2, 2, 2]
    • Expected Output: 1
    • Justification: 1 appears exactly once whereas 99 and 2 each appear three times.
  • Example 3:
    • Input: nums = [0, 7, 2, 7, 2, 7, -1, 2, -1, -1]
    • Expected Output: 0
    • Justification: 0 is the unique number appearing once, while 7, 2 and -1 appear three times.

Solution

To solve this problem, we'll employ bitwise manipulation techniques, which are both space-efficient and run in linear time. The essence of this approach is to count the number of times each bit appears in all numbers. Since every number, except for one, appears exactly three times, a bit set in the unique number will contribute to the total count in a way that's not divisible by three. By iterating over each bit position and summing the occurrence of bits in that position across all numbers, we can determine which bits belong to the unique number. We'll then reconstruct this number from its bits.

This method is effective because it directly leverages the fixed repetition count and the bitwise nature of integers to sidestep the need for additional memory that would be required for hash table-based approaches.

Step-by-Step Algorithm

  1. Initialize a Bit Count Array:

    • Create an array bitCount with a size equal to the number of bits in an integer (32 bits for standard integers). This array will track the count of 1s in each bit position across all numbers in the input array.
  2. Count Bits for Each Number:

    • Iterate over each number in the input array.
    • For each number, iterate over each bit position from 0 to 31.
      • Right shift the number by i bits and apply a bitwise AND with 1 to isolate the bit at position i.
      • Add the result to the ith position in the bitCount array to count the occurrences of 1s in this bit position across all numbers.
  3. Reconstruct the Single Number:

    • Initialize a variable result to 0. This variable will store the unique number that appears exactly once.
    • Iterate over the bitCount array from 0 to 31 (for each bit position).
      • If the count in bitCount[i] is not divisible by 3, it means this bit is set in the unique number (since all other numbers appear exactly three times).
      • Set the ith bit in result by using a bitwise OR with (1 << i).
  4. Return the Unique Number:

    • Return the result, which now contains the unique number reconstructed from its bits.

Algorithm Walkthrough

Let's walkthrough the Input: nums = [0, 7, 2, 7, 2, 7, -1, 2, -1, -1]

  1. Initialize bitCount Array:

    • Before processing: bitCount = [0, 0, 0, ..., 0] (32 zeroes for 32-bit positions).
  2. Process Each Number and Update bitCount:

    • Process 0:

      • No bits to update for 0. bitCount remains unchanged.
    • First 7 encountered:

      • 7 in binary is 000...0111. Update counts for positions 0, 1, and 2.
      • After processing: bitCount = [1, 1, 1, 0, 0, ..., 0].
    • First 2 encountered:

      • 2 in binary is 000...0010. Update count for position 1.
      • After processing: bitCount = [1, 2, 1, 0, 0, ..., 0].
    • Second 7 encountered:

      • Update counts for positions 0, 1, and 2 again.
      • After processing: bitCount = [2, 3, 2, 0, 0, ..., 0].
    • Second 2 encountered:

      • Update count for position 1.
      • After processing: bitCount = [2, 4, 2, 0, 0, ..., 0].
    • Third 7 encountered:

      • Update counts for positions 0, 1, and 2 again.
      • After processing: bitCount = [3, 5, 3, 0, 0, ..., 0].
    • Third 2 encountered:

      • Update count for position 1.
      • After processing: bitCount = [3, 6, 3, 0, 0, ..., 0].
    • First -1 encountered:

      • -1 in binary (two's complement) is all 1s. Update all positions.
      • After processing: bitCount becomes incremented by 1 at each position, e.g., [4, 7, 4, 1, 1, ..., 1].
    • Second -1 encountered:

      • Again, update all positions by 1.
      • After processing: bitCount increments by 1 at each position again, e.g., [5, 8, 5, 2, 2, ..., 2].
    • Third -1 encountered:

      • Once more, update all positions by 1.
      • After processing: bitCount increments by 1 at each position, e.g., [6, 9, 6, 3, 3, ..., 3].
  3. Reconstruct the Single Number:

    • Iterate over bitCount. Look for positions where the count is not a multiple of 3.
    • Since every number except 0 has modified the bitCount, and since 0 does not contribute to any bit position, the only way to detect 0 is by realizing there's no bit position with a count not divisible by 3 that would contribute to constructing a non-zero result.
    • The absence of such positions confirms the unique number does not contribute to any bit's count, identifying the unique number as 0.
  4. Return the Unique Number:

    • The final result is calculated to be 0, which correctly identifies it as the unique number not conforming to the thrice occurrence pattern in the input array.

Code

java
public class Solution {

  // Function to find the single number
  public int singleNumber(int[] nums) {
    int[] bitCount = new int[32]; // Store the count of each bit across all numbers
    // Count bits at each position
    for (int num : nums) {
      for (int i = 0; i < 32; i++) {
        bitCount[i] += (num >> i) & 1;
      }
    }
    int result = 0; // To construct the single number
    // Reconstruct the single number from bit counts
    for (int i = 0; i < 32; i++) {
      if (bitCount[i] % 3 != 0) {
        result |= (1 << i);
      }
    }
    return result;
  }

  public static void main(String[] args) {
    Solution solution = new Solution();
    // Test the solution with the provided examples
    System.out.println(solution.singleNumber(new int[] { 4, 3, 3, 3 })); // Expected 4
    System.out.println(
      solution.singleNumber(new int[] { 99, 1, 99, 99, 2, 2, 2 })
    ); // Expected 1
    System.out.println(
      solution.singleNumber(new int[] { 0, 7, 2, 7, 2, 7, -1, 2, -1, -1 })
    ); // Expected 0
  }
}

Complexity Analysis

Time Complexity

The time complexity is , where (N) is the length of the input array and (K) is the number of bits in an integer (which is a constant, typically 32 for standard integer representations). Since K is constant, the time complexity simplifies to , indicating linear time complexity with respect to the size of the input.

Space Complexity

The space complexity is , due to the additional array bitCount used to keep track of the count of each bit across all numbers in the input array. Since K is a constant (32 for an integer), the space complexity simplifies to , indicating constant space complexity.

🤖 Don't fully get this? Learn it with Claude

Stuck on Single Number II? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🪜 Hint ladder (no spoilers)

Progressively stronger hints — you still solve it.

I'm working on the problem **Single Number II** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🎨 Explain the approach visually

See the technique, not just code.

Explain the optimal approach to **Single Number II** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔍 Review my solution

Catch bugs, edge cases, sub-optimality.

I'll paste my solution to **Single Number II**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🔁 Drill the pattern

Lock in recognition with look-alikes.

Give me 2 problems that use the SAME underlying pattern as **Single Number II**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes