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.

Try It Yourself
redirect icon

[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.

C++
#include <iostream>
#include <vector>
#include <climits>
#include <cmath>
using namespace std;

// Function to find minimum distance between two elements x and y
int minDist(vector<int>& arr, int x, int y) {
    int n = arr.size();  
    
    // Initialize minimum distance to maximum possible value
    int min_dist = INT_MAX; 

    // Traverse every possible pair (i, j)
    for (int i = 0; i < n; i++) {

        for (int j = i + 1; j < n; j++) {

            // Check if current pair matches (x, y) OR (y, x)
            // This ensures we consider both orders
            if ((x == arr[i] && y == arr[j] || 
                 y == arr[i] && x == arr[j]) 
                && min_dist > abs(i - j)) {

                // Update minimum distance if a smaller one is found
                min_dist = abs(i - j);
            }
        }
    }

    // If min_dist was never updated, return -1 (elements not found)
    return min_dist > n ? -1 : min_dist;
}

int main()
{
    vector<int> arr = {10, 20, 30, 40, 50};
    cout << minDist(arr, 10, 50);
    return 0;
}
Java
class GFG {

    // Function to find minimum distance between two elements x and y
    static int minDist(int[] arr, int x, int y) {

        int n = arr.length;
        // Initialize with max value
        int min_dist = Integer.MAX_VALUE;
        
        // Traverse all possible pairs (i, j)
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Check if pair matches (x, y) OR (y, x)
                if ((x == arr[i] && y == arr[j] || 
                     y == arr[i] && x == arr[j])
                        && min_dist > Math.abs(i - j)) {

                    // Update minimum distance
                    min_dist = Math.abs(i - j);
                }
            }
        }

        // If never updated, return -1
        return min_dist > n ? -1 : min_dist;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};

        System.out.println(minDist(arr, 10, 50));
    }
}
Python
# Function to find minimum distance between two elements x and y
def minDist(arr, x, y):

    n = len(arr) 
    # Initialize with infinity
    
    min_dist = float('inf')
    
    # Traverse all possible pairs (i, j)
    for i in range(n):
        for j in range(i + 1, n):

            # Check if pair matches (x, y) OR (y, x)
            if ((x == arr[i] and y == arr[j]) or (y == arr[i] and x == arr[j])) \
               and min_dist > abs(i - j):

                # Update minimum distance
                min_dist = abs(i - j)

    # If never updated, return -1
    return -1 if min_dist > n else min_dist

if __name__ == "__main__": 
    arr = [10, 20, 30, 40, 50]
    print(minDist(arr, 10, 50))
C#
using System;

class GFG {

    // Function to find minimum distance between two elements x and y
    static int minDist(int[] arr, int x, int y) {

        int n = arr.Length; 
        
        // Initialize with max value
        int min_dist = int.MaxValue; 
        
        // Traverse all possible pairs (i, j)
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {

                // Check if pair matches (x, y) OR (y, x)
                if ((x == arr[i] && y == arr[j] || y == arr[i] && x == arr[j])
                    && min_dist > Math.Abs(i - j)) {

                    // Update minimum distance
                    min_dist = Math.Abs(i - j);
                }
            }
        }

        // If never updated, return -1
        return min_dist > n ? -1 : min_dist;
    }

    static void Main() {
        int[] arr = {10, 20, 30, 40, 50};

        Console.WriteLine(minDist(arr, 10, 50));
    }
}
JavaScript
// Function to find minimum distance between two elements x and y
function minDist(arr, x, y) {

    let n = arr.length; 
    
    // Initialize with large value
    let min_dist = Infinity; 

    // Traverse all possible pairs (i, j)
    for (let i = 0; i < n; i++) {
        for (let j = i + 1; j < n; j++) {

            // Check if pair matches (x, y) OR (y, x)
            if (((x === arr[i] && y === arr[j]) || (y === arr[i] && x === arr[j])) 
                && min_dist > Math.abs(i - j)) {

                // Update minimum distance
                min_dist = Math.abs(i - j);
            }
        }
    }

    // If never updated, return -1
    return min_dist > n ? -1 : min_dist;
}

// Driver code 
let arr = [10, 20, 30, 40, 50];
console.log(minDist(arr, 10, 50));

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

C++
#include <iostream>
#include <vector>
#include <climits>
using namespace std;

// returns minimum distance between x and y
int minDist(vector<int>& arr, int x, int y)
{
    int prev = -1, n = arr.size() ;
    
    // large value
    int min_dist = INT_MAX; 

    for (int i = 0; i < n; i++) {
        if (arr[i] == x || arr[i] == y) {

            // update only if previous was different
            if (prev != -1 && arr[i] != arr[prev]) {
                min_dist = min(min_dist, i - prev);
            }
            
            // update last seen index
            prev = i;
        }
    }

    return min_dist > n ? -1 : min_dist;
}

int main()
{
    vector<int> arr = {10, 20, 30, 40, 50};
    cout << minDist(arr, 10, 50);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    
    // returns minimum distance between x and y
    public static int minDist(int[] arr, int x, int y) {
        int prev = -1, n = arr.length;

        // large value
        int min_dist = Integer.MAX_VALUE;

        for (int i = 0; i < n; i++) {
            if (arr[i] == x || arr[i] == y) {

                // update only if previous was different
                if (prev!= -1 && arr[i]!= arr[prev]) {
                    min_dist = Math.min(min_dist, i - prev);
                }

                // update last seen index
                prev = i;
            }
        }

        return min_dist > n ? -1 : min_dist;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        System.out.println(minDist(arr, 10, 50));
    }
}
Python
def minDist(arr, x, y):
    prev = -1
    n = len(arr)

    # large value
    min_dist = float('inf')

    for i in range(n):
        if arr[i] == x or arr[i] == y:

            # update only if previous was different
            if prev!= -1 and arr[i]!= arr[prev]:
                min_dist = min(min_dist, i - prev)

            # update last seen index
            prev = i

    return min_dist if min_dist!= float('inf') else -1

if __name__ == '__main__':
    arr = [10, 20, 30, 40, 50]
    print(minDist(arr, 10, 50))
C#
using System;

public class Program {
    
    // returns minimum distance between x and y
    public static int minDist(int[] arr, int x, int y) {
        int prev = -1, n = arr.Length;

        // large value
        int min_dist = int.MaxValue;

        for (int i = 0; i < n; i++) {
            if (arr[i] == x || arr[i] == y) {

                // update only if previous was different
                if (prev!= -1 && arr[i]!= arr[prev]) {
                    min_dist = Math.Min(min_dist, i - prev);
                }

                // update last seen index
                prev = i;
            }
        }

        return min_dist > n? -1 : min_dist;
    }

    public static void Main() {
        int[] arr = {10, 20, 30, 40, 50};
        Console.WriteLine(minDist(arr, 10, 50));
    }
}
JavaScript
function minDist(arr, x, y) {
    let prev = -1, n = arr.length;

    // large value
    let min_dist = Number.MAX_SAFE_INTEGER;

    for (let i = 0; i < n; i++) {
        if (arr[i] === x || arr[i] === y) {

            // update only if previous was different
            if (prev!== -1 && arr[i]!== arr[prev]) {
                min_dist = Math.min(min_dist, i - prev);
            }

            // update last seen index
            prev = i;
        }
    }

    return min_dist > n ? -1 : min_dist;
}

let arr = [10, 20, 30, 40, 50];
console.log(minDist(arr, 10, 50));

Output
4
Comment