Find the minimum distance between two numbers

Problem:
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}, x = 1, y = 2
Output: Minimum distance between 1 and 2 is 1.

Input: arr[] = {3, 4, 5}, x = 3, y = 5
Output: Minimum distance between 3 and 5 is 2.

Input: arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3},  x = 3, y = 6
Output: Minimum distance between 3 and 6 is 4.

Input: arr[] = {2, 5, 3, 5, 4, 4, 2, 3},  x = 3, y = 2
Output: Minimum distance between 3 and 2 is 1.

Method 1 (Simple)
Our task is to find the distance between two given numbers , So we can find the distance between any two elements using two loops . The outer loop for selecting the first element (x) and the inner loop for traversing the array in search for the other element (y) and taking the minimum distance between them.
Please look at the comments in the code to learn more about implementation.

C++



filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to Find the minimum
// distance between two numbers
#include <bits/stdc++.h>
using namespace std; 
  
int minDist(int arr[], int n, int x, int y)
{
    int i, j;
    int min_dist = INT_MAX;
    for (i = 0; i < n; i++)
    {
        for (j = i+1; j < n; j++)
        {
            if( (x == arr[i] && y == arr[j] ||
                y == arr[i] && x == arr[j]) &&
                min_dist > abs(i-j))
            {
                min_dist = abs(i-j);
            }
        }
    }
    return min_dist;
}
  
/* Driver code */
int main() 
{
    int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 3;
    int y = 6;
  
    cout << "Minimum distance between " << x << 
                    " and " << y << " is " << 
                    minDist(arr, n, x, y) << endl;
}
  
// This code is contributed by Shivi_Aggarwal

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// C program to Find the minimum
// distance between two numbers
#include <stdio.h>
#include <stdlib.h> // for abs()
#include <limits.h> // for INT_MAX
  
int minDist(int arr[], int n, int x, int y)
{
   int i, j;
   int min_dist = INT_MAX;
   for (i = 0; i < n; i++)
   {
     for (j = i+1; j < n; j++)
     {
         if( (x == arr[i] && y == arr[j] ||
              y == arr[i] && x == arr[j]) && min_dist > abs(i-j))
         {
              min_dist = abs(i-j);
         }
     }
   }
   return min_dist;
}
  
/* Driver program to test above function */
int main() 
{
    int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 3;
    int y = 6;
  
    printf("Minimum distance between %d and %d is %d\n", x, y, 
              minDist(arr, n, x, y));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Find the minimum
// distance between two numbers
class MinimumDistance 
{
    int minDist(int arr[], int n, int x, int y) 
    {
        int i, j;
        int min_dist = Integer.MAX_VALUE;
        for (i = 0; i < n; i++) 
        {
            for (j = i + 1; j < n; j++) 
            {
                if ((x == arr[i] && y == arr[j]
                    || y == arr[i] && x == arr[j])
                    && min_dist > Math.abs(i - j)) 
                    min_dist = Math.abs(i - j);
            }
        }
        return min_dist;
    }
  
    public static void main(String[] args) 
    {
        MinimumDistance min = new MinimumDistance();
        int arr[] = {3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
        int n = arr.length;
        int x = 3;
        int y = 6;
  
        System.out.println("Minimum distance between " + x + " and " + y 
                + " is " + min.minDist(arr, n, x, y));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to Find the minimum
# distance between two numbers
  
def minDist(arr, n, x, y):
    min_dist = 99999999
    for i in range(n):
        for j in range(i + 1, n):
            if (x == arr[i] and y == arr[j] or
            y == arr[i] and x == arr[j]) and min_dist > abs(i-j):
                min_dist = abs(i-j)
        return min_dist
  
  
# Driver code
arr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print("Minimum distance between ",x," and ",
     y,"is",minDist(arr, n, x, y))
  
# This code is contributed by "Abhishek Sharma 44"

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# code to Find the minimum
// distance between two numbers
using System;
  
class GFG {
      
    static int minDist(int []arr, int n,
                           int x, int y) 
    {
        int i, j;
        int min_dist = int.MaxValue;
        for (i = 0; i < n; i++) 
        {
            for (j = i + 1; j < n; j++) 
            {
                if ((x == arr[i] && 
                     y == arr[j] || 
                     y == arr[i] && 
                       x == arr[j])
                    && min_dist >
                   Math.Abs(i - j))
                     
                    min_dist =
                    Math.Abs(i - j);
            }
        }
        return min_dist;
    }
      
    // Driver function
    public static void Main()
    {
        int []arr = {3, 5, 4, 2, 6,
              5, 6, 6, 5, 4, 8, 3};
        int n = arr.Length;
        int x = 3;
        int y = 6;
  
        Console.WriteLine("Minimum "
               + "distance between "
         + x +  " and " + y + " is " 
           + minDist(arr, n, x, y));
    }
}
  
// This code is contributed by Sam007

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to Find the minimum 
// distance between two numbers
  
function minDist($arr, $n, $x, $y)
{
    $i; $j;
    $min_dist = PHP_INT_MAX;
    for ($i = 0; $i < $n; $i++)
    {
        for ($j = $i + 1; $j < $n; $j++)
        {
            if( ($x == $arr[$i] and $y == $arr[$j] or
                $y == $arr[$i] and $x == $arr[$j]) and
                             $min_dist > abs($i - $j))
            {
                $min_dist = abs($i - $j);
            }
        }
    }
    return $min_dist;
}
  
    // Driver Code
    $arr = array(3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3);
    $n = count($arr);
    $x = 3;
    $y = 6;
  
    echo "Minimum distance between ",$x, " and ",$y," is "
    echo minDist($arr, $n, $x, $y);
  
// This code is contributed by anuj_67.
?>

chevron_right



Output:

Minimum distance between 3 and 6 is 4

Time Complexity: O(n^2)

Method 2 (Tricky)
In our previous approach, we use two loops(without any jumps) which makes out time complexity to be O(n^2). We will try to reduce that to O(n). So our basic approach this time will be only checking consecutive pairs of x and y . We need not check all values of y for a single element (x) . What we can do is , for every element x or y , we will check the index of previous occurrence of x or y and if the previous occurring element is not similar to current element we will update the minimum distance . But a question arises what if a x is preceded by another x and that is preceded by a y ,then how we get the minimum distance between pairs . By analyzing closely we can see that every x followed by a y or vice versa can only be the closest pair (minimum distance ) so we can ignore all other pairs .

Thanks to wgpshashank for suggesting this approach.

Please look at the comments in the code to learn more about implementation.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
int minDist(int arr[], int n, int x, int y)
{
          
    //previous index and min distance
    int p = -1, min_dist = INT_MAX;
      
    for(int i=0 ; i<n ; i++)
    {
        if(arr[i]==x || arr[i]==y)
        {
            //we will check if p is not equal to -1 and 
            //If the element at current index matches with
            //the element at index p , If yes then update 
            //the minimum distance if needed 
            if( p != -1 && arr[i] != arr[p])
                min_dist = min(min_dist , i-p);
               
            //update the previos index 
            p=i;
        }
    }
    //If distance is equal to int max 
    if(min_dist==INT_MAX)
        return -1;
  
    return min_dist;
}
  
/* Driver code */
int main()
{
    int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    int x = 3;
    int y = 6;
  
    cout << "Minimum distance between " << x <<
                        " and " << y << " is "<<
                        minDist(arr, n, x, y) << endl;
    return 0;
}
  
// This code is contributed by Mukul singh.

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
#include <limits.h> // For INT_MAX
  
//returns minimum of two numbers
int min(int a ,int b)
{
    if(a < b)
        return a;
    return b;
}
  
int minDist(int arr[], int n, int x, int y)
{
    //previous index and min distance
    int i=0,p=-1, min_dist=INT_MAX;
      
    for(i=0 ; i<n ; i++)
    {
        if(arr[i] ==x || arr[i] == y)
        {
            //we will check if p is not equal to -1 and 
            //If the element at current index matches with
            //the element at index p , If yes then update 
            //the minimum distance if needed 
            if(p != -1 && arr[i] != arr[p])
                min_dist = min(min_dist,i-p);
               
            //update the previos index 
            p=i;
        }
    }
    //If distance is equal to int max 
    if(min_dist==INT_MAX)
       return -1;
    return min_dist;
}
  
/* Driver program to test above function */
int main()
{
    int arr[] ={3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
    int n = sizeof(arr)/sizeof(arr[0]);
    int x = 3;
    int y = 6;
  
    printf("Minimum distance between %d and %d is %d\n", x, y,
            minDist(arr, n, x, y));
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

class MinimumDistance
{
    int minDist(int arr[], int n, int x, int y) 
    {
          
    //previous index and min distance
    int i=0,p=-1, min_dist=Integer.MAX_VALUE;
      
    for(i=0 ; i<n ; i++)
    {
        if(arr[i] ==x || arr[i] == y)
        {
            //we will check if p is not equal to -1 and 
            //If the element at current index matches with
            //the element at index p , If yes then update 
            //the minimum distance if needed 
            if(p != -1 && arr[i] != arr[p])
                min_dist = Math.min(min_dist,i-p);
               
            //update the previous index 
            p=i;
        }
    }
    //If distance is equal to int max 
    if(min_dist==Integer.MAX_VALUE)
       return -1;
    return min_dist;
}
  
    /* Driver program to test above functions */
    public static void main(String[] args) {
        MinimumDistance min = new MinimumDistance();
        int arr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
        int n = arr.length;
        int x = 3;
        int y = 6;
  
        System.out.println("Minimum distance between " + x + " and " + y
                + " is " + min.minDist(arr, n, x, y));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

import sys
  
def minDist(arr, n, x, y):
      
    #previous index and min distance
    i=0
    p=-1
    min_dist = sys.maxsize;
      
    for i in range(n): 
      
        if(arr[i] ==x or arr[i] == y):
          
            #we will check if p is not equal to -1 and 
            #If the element at current index matches with
            #the element at index p , If yes then update 
            #the minimum distance if needed 
            if(p != -1 and arr[i] != arr[p]):
                min_dist = min(min_dist,i-p)
               
            #update the previos index 
            p=i
          
      
    #If distance is equal to int max 
    if(min_dist == sys.maxsize):
       return -1
    return min_dist
  
   
# Driver program to test above function */
arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print ("Minimum distance between %d and %d is %d\n"%( x, y,minDist(arr, n, x, y)));
  
# This code is contributed by Shreyanshi Arun.

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to Find the minimum 
// distance between two numbers
using System;
class MinimumDistance {
      
    static int minDist(int []arr, int n,
                       int x, int y) 
    {
    //previous index and min distance
    int i=0,p=-1, min_dist=int.MaxValue;
      
    for(i=0 ; i<n ; i++)
    {
        if(arr[i] ==x || arr[i] == y)
        {
            //we will check if p is not equal to -1 and 
            //If the element at current index matches with
            //the element at index p , If yes then update 
            //the minimum distance if needed 
            if(p != -1 && arr[i] != arr[p])
                min_dist = Math.Min(min_dist,i-p);
               
            //update the previos index 
            p=i;
        }
    }
    //If distance is equal to int max 
    if(min_dist==int.MaxValue)
       return -1;
   
   return min_dist;
}
    // Driver Code
    public static void Main() 
    {
          
        int []arr = {3, 5, 4, 2, 6, 3, 
                     0, 0, 5, 4, 8, 3};
        int n = arr.Length;
        int x = 3;
        int y = 6;
        Console.WriteLine("Minimum distance between " + x + " and " + y
                                       + " is " + minDist(arr, n, x, y));
    }
}
  
// This code is contributed by anuj_67.

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// PHP program to Find the minimum 
// distance between two numbers
  
function minDist($arr, $n, $x, $y)
{
      
    //previous index and min distance
    $i=0;
    $p=-1;
    $min_dist=PHP_INT_MAX;
      
    for($i=0 ; $i<$n ; $i++)
    {
        if($arr[$i] ==$x || $arr[$i] == $y)
        {
            //we will check if p is not equal to -1 and 
            //If the element at current index matches with
            //the element at index p , If yes then update 
            //the minimum distance if needed 
            if($p != -1 && $arr[$i] != $arr[$p])
                $min_dist = min($min_dist,$i-$p);
               
            //update the previous index 
            $p=$i;
        }
    }
    //If distance is equal to int max 
    if($min_dist==PHP_INT_MAX)
       return -1;
    return $min_dist;
}
  
/* Driver program to test above function */
    $arr =array(3, 5, 4, 2, 6, 3, 0, 0, 5,
                                    4, 8, 3);
    $n = count($arr);
    $x = 3;
    $y = 6;
  
    echo "Minimum distance between $x and ",
         "$y is ", minDist($arr, $n, $x, $y);
  
// This code is contributed by anuj_67.
?>

chevron_right



Output:

Minimum distance between 3 and 6 is 1

Time Complexity: O(n)

Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.




My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :


18


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.