My approach to solving HackerRank’s Lonely Integer code challenge.
Given an array of integers, where all elements but one occur twice, find the unique element.
a = [1, 2, 3, 4, 3, 2, 1]
The unique element is 4
.
The first line contains a single integer, n
, the number of integers in the array.
The second line contains n
space-separated integers that describe the values in a
.
Returns int
value of the element that occurs only once.
First, we start by creating a count
function which accepts the value (v
) we want to search for. Within the function, we run the Array.filter()
method to create a new copy of a given array and populate it with the filtered value(s) (v
). Then Array.length
returns the exact number of times the value (v
) appeared in the given array.
After that, we run a classic for
loop where within each iteration, we pass the current array's item to the count()
function and see if the result is equal to 1
. If so, we return the current value (arr[i]
) as it is unique and appears only once.
1function lonelyinteger(a) {2 const count = (v) => a.filter((i) => i == v).length;3
4 for (let i = 0; i < a.length; i++) {5 if (count(a[i]) === 1) {6 return a[i];7 }8 }9}
Sign up to get updates when I write something new. No spam ever.
Subscribe to my Newsletter