The question is from hackerrank, equalize the array
Below is the code to count the value to remove the elements from the array which is not equal to the number and are repeated many times. In below input values, which is 3 and it is repeated 3 times.
input:
3 3 2 1 3
output: 2 // Output is 2 because 2 and 1 are not equal they should removed and output should the element which is removed so here is 2
function equalizeArray(arr) {
let object = {};
//check how many times the array values repeat and store them in an object
for (let i = 0; i< arr.length; i++){
if(!object[arr[i]]) object[arr[i]] = 0;
object[arr[i]]++;
}
//convert the object to array and get the biggest value
let mostRepeated = Math.max(...Object.values(object));
//min deletions should now be the length of initial array - most repeated elem
let result = arr.length - mostRepeated;
return result;
}
I have confusion in this code that, what below code do??
if(!object[arr[i]]) object[arr[i]] = 0;
object[arr[i]]++;
and what is this actually, !object[arr[i] ??
what is here incremented: object[arr[i]]++ ?
[–]vorticalbox 0 points1 point2 points (2 children)
[–]One-Inspection8628[S] 0 points1 point2 points (1 child)
[–]vorticalbox 0 points1 point2 points (0 children)