Single Number

Updated on 02 July, 2025
Single Number header image

Problem Statement

In this problem, you are given a non-empty array of integers, nums, in which every element appears twice except for one unique element. Your task is to identify and return this unique element. The challenge lies in achieving a solution that operates with linear time complexity (O(n)) and does not rely on additional memory beyond constant space. This requires a sophisticated strategy beyond simple counting or hashing approaches, which typically require additional space proportional to the size or range of the data.

Examples

Example 1

Input:

nums = [2,2,1]

Output:

1

Example 2

Input:

nums = [4,1,2,1,2]

Output:

4

Example 3

Input:

nums = [1]

Output:

1

Constraints

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

Approach and Intuition

The key to solving this problem efficiently lies in leveraging bitwise operations, specifically the XOR operation. Below is the intuition and step-by-step approach using XOR:

  1. Understanding XOR Properties: XOR of a number with itself is 0 (e.g., a ^ a = 0) and XOR of a number with 0 is the number itself (e.g., a ^ 0 = a). Additionally, XOR operation is commutative and associative, meaning the order in which numbers are XORed does not affect the result.

  2. Application on the Array:

    • As we know, every element except one appears twice in the array. If we XOR all elements of the array, pairs of identical numbers will cancel each other out because of the property a ^ a = 0.
    • The result will be the number that appears only once because a ^ a ^ b = b where b is the unique element.
  3. Implementing the Solution:

    • Initialize a variable, say result, to 0.
    • Iterate through each number in the array, applying XOR between result and the number, and store the result back into result.
    • By the end of the loop, result will contain the unique number since all other duplicates would cancel out.

This approach is efficient because it requires only one pass through the array, giving a linear runtime complexity, O(n). Furthermore, it uses a constant amount of extra space for the result variable, complying with the space constraint.

Example Explanation based on Provided Examples:

  • For Example 1 (nums = [2,2,1]): XORing all numbers -> 2 ^ 2 ^ 1 = 0 ^ 1 = 1
  • For Example 2 (nums = [4,1,2,1,2]): XORing all numbers -> 4 ^ 1 ^ 2 ^ 1 ^ 2 = 4 ^ 0 ^ 0 = 4
  • For Example 3 (nums = [1]): Since there’s only one element, XORing it with zero results in the number itself -> 0 ^ 1 = 1

Following this approach ensures that you meet both the time complexity and space constraint requirements effectively.

Solutions

  • C++
  • Java
  • C
  • JavaScript
  • Python
cpp
class Solution {
public:
    int findUnique(vector<int>& elements) {
        int result = 0;
        for (int num : elements) {
            result ^= num;
        }
        return result;
    }
};

The given problem, "Single Number," requires finding the number in a list that appears exactly once when every other number appears twice. The solution uses C++ as the programming language.

In this solution, utilize the XOR bitwise operator, which has distinct properties:

  • When a number is XORed with itself, the result is 0.
  • XORing a number with 0 leaves the number unchanged.

This makes XOR particularly useful for this problem, as pairing each number with its duplicate will cancel out the duplicates and leave the unique number.

Here's how the solution processes:

  • Initialize an integer result to 0.
  • Iterate over each element in the vector elements.
  • For each number num, XOR it with result and store the outcome back in result.
  • After completing the loop, result contains the unique number since all paired duplicates have canceled each other.

The function findUnique accepts a vector of integers and returns the unique integer by exploiting the properties of the XOR operation efficiently, ensuring a linear time complexity of O(n) and a constant space complexity.

java
class Solution {
    public int findUnique(int[] array) {
        int result = 0;
        for (int num : array) {
            result ^= num;
        }
        return result;
    }
}

The problem "Single Number" requires finding the element in an array that does not have a duplicate. The algorithm adopted for this solution exploits the properties of the XOR operation, implemented in Java.

  • Start by initializing an integer result to 0. This variable will hold the unique number.
  • Traverse through each number in the array using an enhanced for loop.
  • Apply the XOR operation between result and each element in the array. The XOR of two same numbers is 0, and the XOR of any number with 0 is the number itself. Thus, pairs of duplicate numbers cancel each other out, leaving only the single number.
  • Finally, return result, which now contains the single non-duplicated number.

The approach efficiently finds the unique number with a time complexity of O(n), where n is the number of elements in the array, and a space complexity of O(1), requiring no extra space beyond the input array.

c
// C
int findUnique(int* array, int length) {
    int unique = 0;
    for (int i = 0; i < length; i++) {
        unique ^= array[i];
    }
    return unique;
}

The provided C code snippet offers a solution to finding a unique number in an array where every element except one appears twice. The function findUnique utilizes the XOR operation to accomplish this. XORing all elements of the array ensures that pairs of the same number will cancel out because x XOR x = 0. As a result, the only number left uncancelled will be the unique number.

  • The function findUnique accepts two parameters:

    • int* array - a pointer to the array containing the elements.
    • int length - the number of elements in the array.
  • Inside the function:

    • An integer unique is initialized to zero.
    • A for loop iterates through the array, XORing each element with unique.
    • After completing the loop, unique holds the value of the single number that does not repeat.
  • The function returns the value of unique, which is the non-repeated number in the array.

Use this function by passing the array and its length as arguments, and it will return the number that appears only once.

js
// JavaScript
var findUnique = function (array) {
    let result = 0;
    for (let element of array) {
        result ^= element;
    }
    return result;
};

The problem titled "Single Number" entails finding the unique number in an array where every number except one appears twice. The solution is implemented in JavaScript using the exclusive OR (XOR) operation which is very effective for this type of challenge.

Here is an overview of how the JavaScript function findUnique solves this problem:

  • The function starts by initializing result to 0.
  • It then iterates over each element in the given array.
  • For every iteration, it uses the XOR operator (^) on the result with the current element. The XOR operator has a unique property where a number XORed with itself results in zero, and a number XORed with zero results in the number itself.
  • Thus, by XORing all elements, the elements that appear twice cancel out each other, leaving only the unique number.
  • Finally, the function returns result which holds the unique number from the array.

This approach is efficient with a time complexity of O(n) and space complexity of O(1), making it highly suitable for large datasets.

python
class Solution(object):
    def findSingleNumber(self, numbers: List[int]) -> int:
        result = 0
        for number in numbers:
            result ^= number
        return result

The given Python solution employs the XOR operator to efficiently find a single number in a list where every other number occurs twice. The XOR operation has a unique property where a number XORed with itself results in zero and a number XORed with zero remains unchanged. Using this property, the algorithm iteratively XORs all the numbers in the list. Duplicate numbers cancel each other out due to the XOR operation, leaving only the unique number without a duplicate.

Here is a concise breakdown of the implementation strategy:

  1. Initialize result to 0.
  2. Iterate through each number in the list numbers.
  3. Apply XOR between result and number and store it back in result.
  4. After completing the loop, result holds the non-duplicate number, which is returned.

This solution is effective with a time complexity of O(n), where n is the number of elements in the list, making it suitable for large datasets. The space complexity is O(1) as it uses a constant amount of additional memory.

Comments

No comments yet.