Single Number LeetCode Solution

Here, We see Single Number problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

List of all LeetCode Solution

Single Number LeetCode Solution

Single Number LeetCode Solution

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

Single Number Leetcode Solution C++

class Solution {
    int singleNumber(vector<int>& nums) {
        for(int i=1;i<nums.size();i+=2)
                return nums[i-1];
        return nums[nums.size()-1];
Code language: C++ (cpp)

Single Number Leetcode Solution 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;
}Code language: PHP (php)

Single Number Leetcode Solution JavaScript

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

Single Number Solution Python

class Solution(object):
    def singleNumber(self, nums):
        return reduce(operator.xor, nums)
Code language: Python (python)
Scroll to Top