0
My problem is this; I was solving some exercises of the hacker rank platform and I came across a question that asked me to identify the only value in an array that did not repeat. I couldn’t think of any logic to solve the problem and decided to research, I found some resolutions for the exercise but I didn’t understand the logic behind the codes, could help me understand them ?
Because this first code has a supporting text I was able to partially understand. I understood that the method .filter
creates a new array if you pass the test performed by the higher-order function, so this higher-order function would be the function(value)
?, also did not understand why it is inside the parentheses, it is the parameter of the method .filter
?. I looked at the documentation on these methods .indexOf
and the .lastIndexOf
but I couldn’t understand exactly how they work within that code.
function lonelyInteger(a) {
let unique = a.filter(function(value){
return a.indexOf(value) === a.lastIndexOf(value)
})
return unique[0];
}
But this second code is very abstract for me, I don’t understand why {}
in the variable counts
, why result
is loose like that under the let counts = {}
and the logic of ties for
didn’t make sense to me.
function lonelyinteger(a) {
// Write your code here
let counts = {},
result;
for(let i in a) {
let num = a[i];
counts[num] = counts[num] ? counts[num] + 1 : 1;
for(let j in counts){
if(counts.hasOwnProperty(num)) {
if(counts[j] === 1){
result = j;
}
}
}
}
return result;
}
I know my doubts are basic, but I don’t want to resort to the easiest way to just do Ctrl C + Ctrl V, I really want to understand how to solve the issue.
Source:
first code: https://levelup.gitconnected.com/javascript-algorithm-lonely-integer-4397cd8b6ffc
2nd code: discussion tab of the exercise itself on the site Hacker Rank
The first solution checks whether the index of the first occurrence of a number is equal to the Inus of the last occurrence, if it is equal, the conclusion is that this number appears only once in the array and therefore, it is unique. As for performance, it checks all numbers and for each number executes
indexOf
andlastIndexOf
, is therefore running on O(n 2).– Vander Santos
The second code starts well when creating the object
counts
to function as aset
of the array numbers. It uses at least a daringfor ...in
to go through all numbers in the array and if the number is not acounts
, it adds with the value 1, if already included updates the value to 2 (in a way not so easy to read), then makes a second is to go through all elements ofcount
, transforming a solution that could be O(n) into O(n 2). In the end, the key whose value is equal to 1 is stored inresult
.– Vander Santos
Related: https://answall.com/q/511385/69296
– Luiz Felipe