136. Single Number(Solution || Leetcode easy || Java)

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.

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:

  • -3 * 104 <= nums[i] <= 3 * 104
  • Each element in the array appears twice except for one element which appears only once.

SOLUTION:

class Solution {
public int singleNumber(int[] nums) {
int ans = nums[0];

//If we Xor every number with each other then we will get the number
//that is repeated only in a single loop
for(int i = 1; i < nums.length; i++){
ans ^= nums[i];
}

return ans;
}
}

Runtime1 ms

Beats

100%

Memory50.7 MB

Beats

36.54%

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.