The idea to solve this problem is to sort the input array and then use a sliding window approach to find the minimum absolute difference between two consecutive elements. If we find a new low, then clear the result and add the current elements. Add more elements if the current diff is equal to the lowest diff so far.
class Solution {
fun minimumAbsDifference(arr: IntArray): List<List<Int>> {
val sorted = arr.sorted()
var low = 0
var high = 1
var lowestDiff = Integer.MAX_VALUE
var output = ArrayList<List<Int>>()
while(high < sorted.size){
val diff = Math.abs(sorted[high] - sorted[low])
if(diff < lowestDiff){
lowestDiff = diff
output.clear()
}
if(diff == lowestDiff) output.add(listOf(sorted[low], sorted[high]))
low++
high++
}
return output
}
}
Runtime: 496 ms, faster than 30.77% of Kotlin online submissions for Minimum Absolute Difference.
Memory Usage: 50.9 MB, less than 100.00% of Kotlin online submissions for Minimum Absolute Difference.