educative.io

Educative

Simpler O(n) solution without hashing

A reader asked us the following question:

https://github.com/Oladunjoye/Algorithms/blob/master/firstUnique.js. I feel this is a simple O(n) solution which beginners can grasp easily

Hi,

This is Maida from Educative. The proposed solution uses a HashTable and this is the arrays chapter and we haven’t talked about HashTable yet. That’s why we didn’t include that solution in this lesson. However, we have posted this solution on the Discuss so other learners can see another approach of solving the problem.

function findFirstUnique(arr) {
let frequency = {}
let result
for(let val of arr){
frequency[val] = frequency[val] + 1 || 1
}
for (let val of arr){
if(frequency[val] === 1){
result = val
break
}
}
return result;
}

Best Regards,
Maida| Developer Advocate
educative.io

1 Like