Print minimum difference pair

Share

Problem: For a given array of positive or negative integers, find the pair with minimum difference.

Problem Explanation: For a given array a ={10, 8, -1, 9},  the pair with minimum difference is 8 and 9 with difference 1.

Java Implementation

public void minimumDiffPair(int[] arr) {

    int diff = Integer.MAX_VALUE;
    List<Integer> list = null;

    Arrays.sort(arr);

    for (int i = 0; i < arr.length - 1; i++) {
        if (arr[i + 1] - arr[i] < diff) {
            list = new ArrayList<Integer>();
            diff = Math.abs(arr[i + 1] - arr[i]);
            list.add(arr[i]);
            list.add(arr[i + 1]);
        }
    }

    System.out.println("Pair with minimum difference is: " + list);
    System.out.println("Difference: " + diff);
}

TimeComplexity: O(nLog(n))

Note: If you find any other better way to approach to this problem or you find any issue/error in above code snippets/approaches – please share it in the comments section below and get a chance to enrol free of cost for an online Live Data Structure and Algorithm course (specially designed for interview preparation for software companies like Amazon, Google, Facebook, FlipKart, SnapDeal, HealthKart…)