This is actually a hackerrank interview question I have already solved but I need guidance on how to optimize it for the
- Time
- Space
Given an array of integers, your task is to count the number of duplicate array elements. Duplicate is defined as two or more identical elements. For example, in the array [1, 2, 2, 3, 3, 3], the two twos are one duplicate and so are the three threes.
Function Description
Complete the function
countDuplicates
in the editor below. The function must return an integer denoting the number of non-unique (duplicate) values in the numbers array.
countDuplicates
has the following parameter(s):
numbers[numbers[0],...numbers[n-1]]
: an array of integers to processConstraints
1 ≤ n ≤ 1000
1 ≤ numbers[i] ≤ 1000, 0 ≤ i < nSample Input:
[1, 3, 1, 4, 5, 6, 3, 2]
Sample Output:2
Explanation: The integers 1 and 3 both occur more than once, so we return 2 as our answer.
function countDuplicates(original) {
let counts = {},
duplicate = 0;
original.forEach(function(x) {
counts[x] = (counts[x] || 0) + 1;
});
for (var key in counts) {
if (counts.hasOwnProperty(key)) {
counts[key] > 1 ? duplicate++ : duplicate;
}
}
return duplicate;
}