Find Minimum Difference Between Two Elements in Java
Problem
The minimum difference is the smallest absolute gap between any two distinct elements in the array, regardless of their positions.
Given an array of integers, find the minimum absolute difference between any two of its elements.
Java Program
public class MinDifference {
public static void main(String[] args) {
int[] arr = {8, 3, 15, 21, 5};
int minDiff = Integer.MAX_VALUE;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
int diff = Math.abs(arr[i] - arr[j]); // order doesn't matter once absolute
if (diff < minDiff) minDiff = diff;
}
}
System.out.println("Minimum difference: " + minDiff);
}
}Output
Core Logic
Trying every pair of elements and keeping the smallest absolute gap found checks every possible pairing directly.
- 1The outer loop picks one index
i, and the inner loop picks every later indexj, so each pair is checked exactly once. - 2
Math.abs(arr[i] - arr[j])computes the absolute difference for that pair, regardless of which value is larger. - 3Whenever that difference beats
minDiff,minDiffis updated to it. - 4After every pair has been checked,
minDiffholds the smallest gap found.
[8, 3, 15, 21, 5], the pair (3, 5) gives an absolute difference of 2, the smallest of any pair checked.Key Point: Math.abs() is what makes the order of arr[i] and arr[j] irrelevant — the gap between two values is the same regardless of which one is subtracted from which.
Why: Every pair of elements is checked explicitly, so the number of comparisons grows with the square of the array's length.
Key Concepts
Approach 2: Sorting
import java.util.Arrays;
public class MinDifferenceSorted {
public static void main(String[] args) {
int[] arr = {8, 3, 15, 21, 5};
Arrays.sort(arr);
int minDiff = Integer.MAX_VALUE;
for (int i = 1; i < arr.length; i++) {
minDiff = Math.min(minDiff, arr[i] - arr[i - 1]); // sorted, so this is always non-negative
}
System.out.println("Minimum difference: " + minDiff);
}
}
Output
Core Logic
Once the array is sorted, the smallest gap between any two elements is guaranteed to sit between two neighbors — no non-adjacent pair can beat every adjacent one.
- 1
Arrays.sort(arr)puts the array into ascending order. - 2A single pass then compares only consecutive elements,
arr[i] - arr[i - 1], since the array is sorted this is always non-negative. - 3
Math.min(minDiff, ...)keeps the smallest adjacent gap seen so far. - 4After the pass,
minDiffholds the answer — checking only n - 1 adjacent pairs instead of every possible pair.
[8, 3, 15, 21, 5] gives [3, 5, 8, 15, 21]; the adjacent gaps are 2, 3, 7, and 6 — the smallest is 2, between 3 and 5.Key Point: In a sorted array, the closest two values are always next to each other — this is why only adjacent gaps need checking, instead of every one of the O(n²) possible pairs.
Why: Sorting the array in place costs O(n log n), and the single pass over adjacent elements afterward adds only O(n) more.