Minimum Absolute Difference in an Array HackerRank Solution

Minimum Absolute Difference in an Array HackerRank Solution

In this Minimum Absolute Difference HackerRank solution,The absolute difference is the positive difference between two values  and , is written  or  and they are equal. If  and . Given an array of integers, find the minimum absolute difference between any two elements in the array.

Problem Solution in Java

public static int minimumAbsoluteDifference(List<Integer> arr) {
    int minimum = Integer.MAX_VALUE;


    List<Integer> allElUnique = arr.stream()
            .distinct()
            .collect(Collectors.toList());


    if (allElUnique.size() != arr.size()) {
        return 0;
    } else {
        Collections.sort(arr);
        for (int i = 0; i < arr.size() - 1; i++) {
            int left = arr.get(i);
            int right = arr.get(i+1);
            int diff = Math.abs(right - left);
            if (diff < minimum) {
                minimum = diff;
            }
        }
    }
    return minimum;
}
Solve original Problem on HackerRank here. Checkout more HackerRank Problems