Single Number LeetCode Solution - The Coding Shala
Home >> LeetCode >> Single Number
Other Posts You May Like
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; } }
- LeetCode - Bulb Switcher
- Hackerrank - New Year Chaos
- LeetCode - Climbing Stairs
- LeetCode - Swap Nodes in Pairs
- Simple XML Validator
Comments
Post a Comment