The Single Number Problem

Woodelin florveus
2 min readOct 17, 2021

I was tackling a few problems from LeetCode and stumbled upon a problem that resonated with me. The Single Number problem, this particular question requires me to single out the non-repeating digit. My first initial thought process was to sort the numbers in the array. Once completed I created a condition that checks if the integer repeats before it and after it then return it. Which worked out in the long run.

problem

Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. check out the example below.

Input: nums = [4,1,2,1,2]
Output: 4
Input: nums = [2,2,1]
Output: 1

Let's Break it Down

I started by creating a variable that sorts the number for example.

function singleNumber(nums){    let sortNum = nums.sort(function(a,b){a - b})}

I looped through the sorted numbers in the array then proceeded to add the conditional statement. The statement states if the current number does not equal the value or type after, and before it. Here is a better look below.

function singleNumber(nums){    let sortNum = nums.sort(function(a,b){a - b})

for(let i = 0; i < sortNum.length; i++){
if(sortNum[i] !== sortNum[i+1] && sortNum[i] !== sortNum[i - 1]){

}
}
}

If the condition checked out I would simply return that number that does not repeat. here is a better look below.

function singleNumber(nums){let sortNum = nums.sort(function(a,b){a - b})

for(let i = 0; i < sortNum.length; i++){
if(sortNum[i] !== sortNum[i+1] && sortNum[i] !== sortNum[i - 1]{
return sortNum[i]
}
}

here is a full look at the problem.

function singleNumber(nums){let sortNum = nums.sort(function(a,b){a - b})

for(let i = 0; i < sortNum.length; i++){
if(sortNum[i] !== sortNum[i+1] && sortNum[i] !== sortNum[i - 1]){
return sortNum[i]
}
}
}console.log(singleNumber([1,1,4]))

Thanks for reading, till next time coders.

--

--