Single Number LeetCode Solution

Last updated on January 20th, 2025 at 04:15 am

Here, we see the Single Number LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.

List of all LeetCode Solution

Topics

Bit-Manipulation, Hash Table

Companies

Airbnb, Palantir

Level of Question

Easy

Single Number LeetCode Solution

Single Number LeetCode Solution

1. Problem Statement

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.

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

2. Coding Pattern Used in Solution

The JavaJavaScript, and Python implementations use the Bitwise XOR pattern. The C++ implementation uses a Sorting and Pair Comparison approach.

3. Code Implementation in Different Languages

3.1 Single Number C++

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        for(int i=1;i<nums.size();i+=2)
        {
            if(nums[i]!=nums[i-1])
                return nums[i-1];
        }
        return nums[nums.size()-1];
    }
};

3.2 Single Number Java

class Solution {
    public int singleNumber(int[] nums) {
        int res = 0;
    for (int i = 0; i < nums.length; i++) {
        res = res^nums[i];
    }
    return res;
    }
}

3.3 Single Number JavaScript

var singleNumber = function(nums) {
    let uniqNum = 0;
    for (let idx = 0; idx < nums.length; idx++) {
        uniqNum = uniqNum ^ nums[idx];
    } return uniqNum;  
};

3.4 Single Number Python

class Solution(object):
    def singleNumber(self, nums):
        return reduce(operator.xor, nums)

4. Time and Space Complexity

Time ComplexitySpace Complexity
C++O(n log n)O(1)
JavaO(n)O(1)
JavaScriptO(n)O(1)
PythonO(n)O(1)
  • C++ Code:
    • The C++ implementation is less efficient due to the sorting step, which dominates the time complexity.
    • It uses a Sorting and Pair Comparison approach.
  • Java, JavaScript, and Python Code:
    • These implementations are more efficient, leveraging the Bitwise XOR pattern.
    • XOR is a constant-time operation, making these solutions linear in time complexity.
  • Space Complexity:

Scroll to Top