Leetcode problem 18 - Single Number
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
/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
let single = 0;
for (let i = 0; i < nums.length; i++) {
single ^= nums[i];
}
return single;
};
The function takes an array of integers called nums
as input.
It initializes a variable single
to 0. This variable will be used to keep track of the single element that appears only once in the array.
The function then enters a for
loop that iterates through all the elements in the nums
array.
Inside the loop, the XOR (^) operation is used to update the value of the single
variable. The XOR operation has the property that if two bits are different, the result is 1; otherwise, the result is 0. When applied to integers, XORing two identical numbers will result in 0. Since every element in the array appears twice except for one, XORing all the elements together will eventually cancel out the duplicate elements, leaving only the single element that appears once.
The loop continues iterating through the elements, and the XOR operation updates the single
variable accordingly.
After the loop finishes, the function returns the value of the single
variable, which now holds the single element that appears only once in the array.
Loop through the elements of nums: First iteration: single = 0 ^ 4 = 4. Second iteration: single = 4 ^ 1 = 5. Third iteration: single = 5 ^ 2 = 7. Fourth iteration: single = 7 ^ 1 = 6. Fifth iteration: single = 6 ^ 2 = 4.
Leave a comment