Single Number II

Updated on 24 June, 2025
Single Number II header image

Problem Statement

In this task, you're given an integer array nums where each number occurs three times except for one unique element that appears only once. You need to identify and return this unique element. The challenge stipulates finding the solution with a time complexity of O(n), which means you must examine each number ideally just once. Additionally, the space complexity needs to be constant, O(1), thus you cannot use any additional significant memory proportional to the input size.

Examples

Example 1

Input:

nums = [2,2,3,2]

Output:

3

Example 2

Input:

nums = [0,1,0,1,0,1,99]

Output:

99

Constraints

  • 1 <= nums.length <= 3 * 104
  • -231 <= nums[i] <= 231 - 1
  • Each element in nums appears exactly three times except for one element which appears once.

Approach and Intuition

To solve the problem efficiently under the given constraints, we can consider the following approach:

  1. Understanding the Bit Manipulation Technique: Given that each number except one appears three times, and we need a constant space solution, bit manipulation forms a natural choice. By manipulating bits, we can focus on counting how many times each bit position becomes '1' across all numbers in the array. For a number that appears three times, each bit in its binary form will contribute thrice to the total count of ones in that particular bit position.

  2. Implementing the 'Three-State Logic' with Bitwise Operations: The idea is to use two integers to represent three states. The states can be thought of as the number of times a bit has been set to 1 modulo 3:

    • ones - This will hold the bits which have appeared 1 time mod 3
    • twos - This will hold the bits which have appeared 2 times mod 3
    • Any bit that appears three times should not affect our result—hence the importance of reseting bits appearing three times.
  3. Algorithm Steps:

    • Initialize two integers, ones and twos, to zero.
    • For each number in the array:
      • Update ones with the current number, keeping in mind the numbers that have previously appeared once and twice.
      • Update twos for numbers that now have appeared twice or ones that were already present as twos.
      • Reset the bits in ones and twos where the count goes up to three. This ensures that bits only contribute to the positions where the corresponding numbers appear exactly once or twice (and not thrice after reset).
    • At the end of the loop, ones will represent the bits of the number that appears exactly once in the array, while twos should ideally be all zeros.
  4. Return Value: The value stored in ones after processing all elements will be the single number which does not appear three times.

This approach manipulates bits across all numbers in a linear pass, keeping track of the count of set bits and using extra variables without allocating extra space proportional to the input size. It cleverly harnesses the power of bitwise operations to maintain count modulo three efficiently, satisfying both the given time and space complexity requirements.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int findSingleNumber(vector<int>& elements) {
        int high = 0, low = 0;
        for (int element : elements) {
            int nextLow = (~high & ~low & element) | (low & ~element);
            int nextHigh = (low & element) | (high & ~element);
            low = nextLow;
            high = nextHigh;
        }
        return low;
    }
};

The programming problem "Single Number II" entails finding a number in an array that appears exactly once while every other number appears three times. The solution provided is implemented in C++ and uses bitwise manipulation to solve the problem efficiently without extra memory for hashing or counters.

  • In the solution, findSingleNumber function takes a vector of integers as input.
  • Two bitwise counters high and low are used to account for the number of times bits appear in the elements.
  • Use a for loop to iterate through each element in the vector.
  • Calculate nextLow considering the current bits not contributing to high and low, and including the bits that turn the current count in low to zero.
  • Calculate nextHigh by evaluating the presence of bits considering transitions triggered by the current element and the states of low and high.
  • Update the states of low and high to nextLow and nextHigh respectively after processing each element.
  • After processing all elements, the value of low represents the unique number as the bits of the high order of triplet bits will be zeroed out.
  • Return low which holds the single number not repeated thrice.

This approach works within linear time complexity O(n) and constant space complexity O(1), ensuring an optimum and practical solution for large datasets.

java
class Solution {
    public int findSingle(int[] array) {
        int firstBit = 0, secondBit = 0;

        for (int value : array) {
            int tempFirstBit = (~firstBit & ~secondBit & value) | (secondBit & ~value);
            int tempSecondBit = (secondBit & value) | (firstBit & ~value);
            secondBit = tempSecondBit;
            firstBit = tempFirstBit;
        }

        return firstBit;
    }
}

The problem titled "Single Number II" is effectively solved using a Java implementation that identifies the element in an array which appears exactly once, while all other elements appear three times. The solution utilizes bitwise operations to achieve this without extra space for storing counts, which can be memory intensive.

The approach is detailed in the Java method findSingle. It uses two variables firstBit and secondBit to track the appearance of bits across all numbers in the array:

  • Iterate through each value in the provided array.
  • For each iteration, calculate tempFirstBit and tempSecondBit based on the current values of firstBit, secondBit, and the bit in the current array value. These calculations make use of bitwise AND, OR, and NOT operators to differentiate between the bits that have appeared once, twice, or three times.
  • Update secondBit and firstBit with the values from tempSecondBit and tempFirstBit respectively.

Finally, return firstBit, which contains the unique number that appears once in the array. This method ensures an efficient computation with a constant space complexity, leveraging the properties of bitwise operations to eliminate the need for additional data structures that track the frequency of each number.

c
int findSingle(int* arr, int size) {
    int upper = 0, lower = 0;
    for (int index = 0; index < size; index++) {
        int temp_lower = (~upper & ~lower & arr[index]) | (lower & ~arr[index]);
        int temp_upper = (lower & arr[index]) | (upper & ~arr[index]);
        lower = temp_lower;
        upper = temp_upper;
    }
    return lower;
}

The provided solution is for the Single Number II problem implemented in C. In this problem, every element appears three times except for one, which appears exactly once. The function findSingle efficiently identifies this unique element using bitwise operations.

Here's what happens in the provided code:

  • The function findSingle accepts two arguments:

    • arr (pointer to an array of integers)
    • size (the number of elements in the array)
  • Two integer variables, upper and lower, are initialized to 0. These variables serve to maintain the count of bits encountered so far in a form that is modulo 3.

  • A for-loop iterates over each element of the array. Two temporary variables, temp_lower and temp_upper, are used within the loop to adjust the count of bits based on the current element arr[index].

    • temp_lower computes the new value for the lower variable. It combines bits that should increment from the lower count or reset based on the current bit value of arr[index].

    • temp_upper computes the new value for the upper variable. It controls the transition of bits that have been counted twice and are either reset or moved to a higher count due to the current bit.

  • After iterating through all elements, lower holds the integer value of the element that appears exactly once. This value is returned by the function.

This solution leverages bitwise operations to keep the space complexity low, using only fixed extra space regardless of the input size. Remember, this solution assumes that every number except one appears exactly three times, which ensures the algorithm's correctness within this specific context.

js
var uniqueNumberFinder = function (array) {
    let lowerBit = 0,
        higherBit = 0;
    for (let value of array) {
        let nextLowerBit = (~higherBit & ~lowerBit & value) | (lowerBit & ~value);
        let nextHigherBit = (lowerBit & value) | (higherBit & ~value);
        lowerBit = nextLowerBit;
        higherBit = nextHigherBit;
    }
    return lowerBit;
};

The provided JavaScript solution addresses the problem of finding a unique number within an array where every other number appears exactly three times except for one, which appears exactly once. The code operates by using bitwise operations to maintain counts of the bits observed in the numbers from the array.

Here's how the implementation works:

  • The function uniqueNumberFinder takes an array of integers as input.
  • Two variables, lowerBit and higherBit, are initialized to zero. These variables are used to track the 1s count in current processing of numbers in the array in the form of bits at two different stages.
  • A loop iterates through each value in the array. Within the loop:
    • nextLowerBit calculates the new state of lowerBit after considering the current number, using bitwise AND, NOT, and OR operations. This calculates whether a bit has been observed once.
    • nextHigherBit calculates the possible transition from a bit being counted once (lowerBit) to being counted a second time (higherBit).
    • The values of lowerBit and higherBit are updated based on the nextLowerBit and nextHigherBit.
  • After processing all numbers in the array, the lowerBit contains the unique number that appears once, as it does not reach a count of three (which would reset the bits to zero).

By using this method, the function efficiently identifies the unique number using a constant amount of space and linear time in respect to the number of integers in the input array. Make sure to encapsulate number entries of integers and not mix explicitly typed data to avoid potential unforeseen behavior due to type conversion. This solution is optimal for handling large datasets with minimal memory overhead.

python
class Solution:
    def findSingle(self, numbers: List[int]) -> int:
        high_bit, low_bit = 0, 0

        for number in numbers:
            temp_low = (~high_bit & ~low_bit & number) | (low_bit & ~number)
            temp_high = (low_bit & number) | (high_bit & ~number)
            low_bit = temp_low
            high_bit = temp_high

        return low_bit

The provided solution addresses the problem of finding a single number that appears exactly once in a list, where all other numbers appear three times. Written in Python, the solution employs a bitwise manipulation method to effectively identify and return the non-repeating element.

  • Use two bit masks, low_bit and high_bit, to track occurrences of bits across all numbers.
  • Iterate through each number in the list:
    • Calculate temp_low to determine bits that should be considered '1' in low_bit.
    • Calculate temp_high to adjust bits that turn from low frequency to high frequency.
    • Update low_bit and high_bit accordingly.
  • After processing all numbers, low_bit will store the bits forming the single number.

This approach efficiently handles the problem using bitwise operations, ensuring that the algorithm operates in linear time and constant space, making it suitable for large datasets. The final output of the function is the unique number in the list.

Comments

No comments yet.