VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-minimum-difference-pair/

⇱ Minimum difference pair in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum difference pair in an array

Last Updated : 12 May, 2026

Given an unsorted array, find the minimum difference between any pair in the given array.

Examples :

Input: [1, 5, 3, 19, 18, 25]
Output: 1
Explanation: Minimum difference is between 18 and 19

Input: [30, 5, 20, 9]
Output: 4
Explanation: Minimum difference is between 5 and 9

Input: [1, 19, -4, 31, 38, 25, 100]
Output: 5
Explanation: Minimum difference is between 1 and -4

[Naive Approach] Using Nested Loops – O(n²) Time and O(1) Space

The idea is to compare every possible pair of elements in the array and calculate their absolute differenceand keep track of the minimum diff.

  • Initialize the minimum difference as infinity
  • Use two nested loops to generate all possible pairs
  • Compute absolute difference for each pair and update minimum value
  • Return the smallest difference obtained after all comparisons

Output
Minimum difference is 1

[Efficient Approach] Using Sorting – O(n log n) Time and O(1) Space

The idea is to first sort the array so that elements with the smallest difference become adjacent to each other. After sorting, instead of checking all possible pairs, we only compare consecutive elements. This works because the minimum difference in a sorted array will always occur between neighboring elements, making the approach much more efficient.

  • Sort the array in non-decreasing order
  • Initialize the minimum difference as infinity
  • Traverse the sorted array and compare adjacent elements
  • Update and return the smallest difference found

Output
Minimum difference is 1
Comment
Article Tags: