Single Number LeetCode Solution - The Coding Shala

Home >> LeetCode >> Single Number

 In this post, we will learn how to solve LeetCode's Single Number Problem and will implement its solution in Java.

Single Number Problem

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

Practice this problem on LeetCode(Click Here).

Single Number Java Solution

Approach 1

We can use the bitwise xor (^) operation. We know that the xor of two same numbers is zero and the xor of a number with zero is the same as the number.

Time Complexity: O(n).

Space Complexity: O(1).

Java Program: 

class Solution {
    public int singleNumber(int[] nums) {
        int ans = nums[0];
        //xor of two same numbers is zero
        for(int i=1; i<nums.length; i++) {
            ans = ans ^ nums[i];
        }
        return ans;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala