The Indian Engineer

Problem 136 Single Number

Posted on Last edited 2 mins

Bit-Manipulation Vectors Bitwise-Xor

Problem Statement

Link - Problem 136

Question

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

You must implement a solution with a linear runtime complexity and use only constant extra space.

Note

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

Solution

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        int ans = nums[0];
        for(int i= 1; i<nums.size(); i++)
            ans = ans^nums[i];
        return ans;

    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation

This solution shows the power of XOR operation. XOR operation is commutative and associative. So, we can use it to find the single number in the array.