I wrote the below code to solve a prep test, found online. The goal is to find the min absolute difference between numbers in an array.
function minimumAbsoluteDifference(arr: number[]): number {
// Write your code here
let res = 0
const length = arr.length
let diff : number
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
if (i !== j) {
diff = Math.abs(arr[i] - arr[j])
if (diff < res || res === 0)
res = diff
}
}
}
return res
}
i ran tests on Math.abs()
, and these days it is faster than a bitshift version... It seems that the only way to make this faster, is either with a reduce, or create a hash to optimize the nested array version.
Any ideas how to rewrite this with reduce()
?
Actually, no reduce is needed. I figured this one out.
The point here, is that for the difference to be minimal, the numbers have to be close. Therefore, we just need to sort the array, then do a for loop with:
diff = Math.min(Math.abs(sorted[i] - sorted[i - 1]), diff)
This removed the need to run the nested loop, and solved the performance issue.