June 26th 2023

Single Number — Typescript

Problem Description permalink

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.

Solution permalink

function singleNumber(nums: number[]): number {
let value = nums[0]
for (var i = 1; i < nums.length; i++) {
value ^= nums[i]
}
return value
};

console.log(singleNumber([2, 2, 1]))
console.log(singleNumber([4, 1, 2, 1, 2]))
console.log(singleNumber([1]))

Discussion permalink

I only know how to do this because I got a CS degree. yaaaaayyyyyy