The Single Number Problem

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.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Kubernetes (Single node) Cluster on a 5$/month VPS

Lazy Loading in Entity Framework

Comparison and Contrast between most popular mobile app development frameworks

How I messed up my Amsterdam pictures by trying to develop C-41 at home

My Construct Week Project

A Beginner Introduction to Ruby Gem Pry

Automated Web Testing: How to Create a Web Test in 2 Minutes with TestCafe Studio

Nabox Weekly Issue 44

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
Woodelin florveus

Woodelin florveus

More from Medium

How to tackle Remote Pair Programming as a novice

Today we talk about some of algorithms like Sliding Window technique.

Open Source v/s Proprietary Software

Knowledge is the best fruit