VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-minimum-distance-between-two-numbers/

⇱ Minimum distance between two in an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum distance between two in an array

Last Updated : 5 Apr, 2026

Given an unsorted array arr[] and two numbers x and y, find the minimum distance between x and y in arr[]. The array might also contain duplicates. You may assume that both x and y are different and present in arr[].

Examples:

Input: arr[] = [1, 2, 3, 2], x = 1, y = 2
Output: 1
Explanation: x = 1 and y = 2. There are two distances between x and y, which are 1 and 3 out of which the least is 1.

Input: arr[] = [86, 39, 90, 67, 84, 66, 62], x = 42, y = 12
Output: -1
Explanation: x = 42 and y = 12. We return -1 as x and y don't exist in the array.

Input: arr[] = [10, 20, 30, 40, 50], x = 10, y = 50
Output: 4
Explanation: The distance between x = 10 (index 0) and y = 50 (index 4) is 4, which is the only distance between them.

[Naive Approach] Using Brute Force - O(n * n) Time and O(1) Space

Find the distance between any two elements using nested loops. The outer loop selects the first element (x), and the inner loop traverses the array to find the other element (y), computing the distance |i - j| and keeping track of the minimum.


Output
4

[Expected Approach] Single Pass - O(n) Time and O(1) Space

Traverse the array once and keep track of the last seen index (prev) of either x or y. Whenever we encounter. For every element, we check if the previous occurrence was the other element (i.e., x after y or y after x). If yes, we compute the distance (current_index - prev) and update the minimum. This works because the closest pair must always be formed by consecutive occurrences of x and y, so all other pairs can be ignored.

Example : arr = [1, 2, 3, 2, 1] , x = 1, y = 2
Initialize: prev = -1, min_dist = INF ( very large value)

Step 1: i = 0 -> arr[0] = 1, First occurrence -> set prev = 0
Step 2: i = 1 -> arr[1] = 2, Previous element was different (1) -> distance = 1 - 0 = 1 -> min_dist = 1, Update prev = 1
Step 3: i = 2 -> arr[2] = 3, Not x or y -> ignore
Step 4: i = 3 -> arr[3] = 2, Same as previous (2) -> no update, Update prev = 3
Step 5: i = 4 -> arr[4] = 1, Previous element was different (2) -> distance = 4 - 3 = 1 -> min_dist = 1, Update prev = 4

-> so min_dist = 1


Output
4
Comment
Article Tags:
Article Tags: