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[].
Input: arr[] = {1, 2}, x = 1, y = 2
Output: Minimum distance between 1
and 2 is 1.
Explanation: 1 is at index 0 and 2 is at
index 1, so the distance is 1
Input: arr[] = {3, 4, 5}, x = 3, y = 5
Output: Minimum distance between 3
and 5 is 2.
Explanation:3 is at index 0 and 5 is at
index 2, so the distance 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.
Explanation:3 is at index 0 and 6 is at
index 5, so the distance 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.
Explanation:3 is at index 7 and 2 is at
index 6, so the distance is 1
Method 1:
Approach:
The task is to find the distance between two given numbers, So find the distance between any two elements using nested 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.
Algorithm:
Create a variable m = INT_MAX
Run a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1
to end (loop counter j).
If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i)
printf("Minimum distance between %d and %d is %d\n", x,
y, minDist(arr, n, x, y));
return0;
}
Java
classMinimumDistance {
intminDist(intarr[], intn, intx, inty)
{
inti, j;
intmin_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);
}
}
if(min_dist > n) {
return-1;
}
returnmin_dist;
}
publicstaticvoidmain(String[] args)
{
MinimumDistance min = newMinimumDistance();
intarr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
intn = arr.length;
intx = 0;
inty = 6;
System.out.println("Minimum distance between "+ x
+ " and "+ y + " is "
+ min.minDist(arr, n, x, y));
}
}
Python3
defminDist(arr, n, x, y):
min_dist =99999999
fori inrange(n):
forj inrange(i +1, n):
if(x ==arr[i] andy ==arr[j] or
y ==arr[i] andx ==arr[j]) andmin_dist > abs(i-j):
min_dist =abs(i-j)
returnmin_dist
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))
C#
usingSystem;
classGFG {
staticintminDist(int[]arr, intn,
intx, inty)
{
inti, j;
intmin_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);
}
}
returnmin_dist;
}
publicstaticvoidMain()
{
int[]arr = {3, 5, 4, 2, 6,
5, 6, 6, 5, 4, 8, 3};
intn = arr.Length;
intx = 3;
inty = 6;
Console.WriteLine("Minimum "
+ "distance between "
+ x + " and "+ y + " is "
+ minDist(arr, n, x, y));
}
}
PHP
<?php
functionminDist($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);
}
}
}
if($min_dist>$n)
{
return-1;
}
return$min_dist;
}
$arr= array(3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3);
$n= count($arr);
$x= 0;
$y= 6;
echo"Minimum distance between ",$x, " and ",$y," is ";
echominDist($arr, $n, $x, $y);
?>
Javascript
<script>
functionminDist(arr, n, x, y)
{
vari, j;
varmin_dist = Number.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);
}
}
if(min_dist>n)
{
return-1;
}
returnmin_dist;
}
vararr = [ 3, 5, 4, 2, 6, 5,
6, 6, 5, 4, 8, 3 ];
varn = arr.length;
varx = 3;
vary = 6;
document.write("Minimum distance between "+ x +
" and "+ y + " is "+
minDist(arr, n, x, y));
</script>
Output
Minimum distance between 3 and 6 is 4
Complexity Analysis:
Time Complexity: O(n^2), Nested loop is used to traverse the array.
Space Complexity: O(1), no
extra space is required.
Method 2:
Approach: So the basic approach is to check only consecutive pairs of x and y. For every element x or y, check the index of the previous occurrence of x or y and if the previous occurring element is not similar to current element update the minimum distance. But a question arises what if an x is preceded by another x and that is preceded by a y, then how to get the minimum distance between
pairs. By analyzing closely it can be seen that every x followed by a y or vice versa can only be the closest pair (minimum distance) so ignore all other pairs.
Algorithm:
Create a variable prev=-1 and m= INT_MAX
Traverse through the array from start to end.
If the current element is x or y, prev is not equal to -1 and array[prev] is not equal to current element then update m = max(current_index – prev, m), i.e. find the
distance between consecutive pairs and update m with it.
print the value of m
Thanks to wgpshashank for suggesting this approach.
Implementation.
C++
#include <bits/stdc++.h>
usingnamespacestd;
intminDist(intarr[], intn, intx, inty)
{
intp = -1, min_dist = INT_MAX;
for(inti=0 ; i<n ; i++)
{
if(arr[i]==x || arr[i]==y)
{
if( p != -1 && arr[i] != arr[p])
min_dist = min(min_dist , i-p);
p=i;
}
}
if(min_dist==INT_MAX)
return-1;
returnmin_dist;
}
intmain()
{
intarr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
intn = sizeof(arr) / sizeof(arr[0]);
intx = 3;
inty = 6;
cout << "Minimum distance between "<< x <<
" and "<< y << " is "<<
minDist(arr, n, x, y) << endl;
return0;
}
C
#include <stdio.h>
#include <limits.h> // For INT_MAX
intmin(inta ,intb)
{
if(a < b)
returna;
returnb;
}
intminDist(intarr[], intn, intx, inty)
{
inti=0,p=-1, min_dist=INT_MAX;
for(i=0 ; i<n ; i++)
{
if(arr[i] ==x || arr[i] == y)
{
if(p != -1 && arr[i] != arr[p])
min_dist = min(min_dist,i-p);
p=i;
}
}
if(min_dist==INT_MAX)
return-1;
returnmin_dist;
}
intmain()
{
intarr[] ={3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
intn = sizeof(arr)/sizeof(arr[0]);
intx = 3;
inty = 6;
printf("Minimum distance between %d and %d is %d\n", x, y,
minDist(arr, n, x, y));
return0;
}
Java
classMinimumDistance
{
intminDist(intarr[], intn, intx, inty)
{
inti=0,p=-1, min_dist=Integer.MAX_VALUE;
for(i=0; i<n ; i++)
{
if(arr[i] ==x || arr[i] == y)
{
if(p != -1&& arr[i] != arr[p])
min_dist = Math.min(min_dist,i-p);
p=i;
}
}
if(min_dist==Integer.MAX_VALUE)
return-1;
returnmin_dist;
}
publicstaticvoidmain(String[] args) {
MinimumDistance min = newMinimumDistance();
intarr[] = {3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3};
intn = arr.length;
intx = 3;
inty = 6;
System.out.println("Minimum distance between "+ x + " and "+ y
+ " is "+ min.minDist(arr, n, x, y));
}
}
Python3
importsys
defminDist(arr, n, x, y):
i=0
p=-1
min_dist =sys.maxsize;
fori inrange(n):
if(arr[i] ==x orarr[i] ==y):
if(p !=-1andarr[i] !=arr[p]):
min_dist =min(min_dist,i-p)
p=i
if(min_dist ==sys.maxsize):
return-1
returnmin_dist
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)));
C#
usingSystem;
classMinimumDistance {
staticintminDist(int[]arr, intn,
intx, inty)
{
inti=0,p=-1, min_dist=int.MaxValue;
for(i=0 ; i<n ; i++)
{
if(arr[i] ==x || arr[i] == y)
{
if(p != -1 && arr[i] != arr[p])
min_dist = Math.Min(min_dist,i-p);
p=i;
}
}
if(min_dist==int.MaxValue)
return-1;
returnmin_dist;
}
publicstaticvoidMain()
{
int[]arr = {3, 5, 4, 2, 6, 3,
0, 0, 5, 4, 8, 3};
intn = arr.Length;
intx = 3;
inty = 6;
Console.WriteLine("Minimum distance between "+ x + " and "+ y
+ " is "+ minDist(arr, n, x, y));
}
}
PHP
<?php
functionminDist($arr, $n, $x, $y)
{
$i=0;
$p=-1;
$min_dist=PHP_INT_MAX;
for($i=0 ; $i<$n; $i++)
{
if($arr[$i] ==$x|| $arr[$i] == $y)
{
if($p!= -1 && $arr[$i] != $arr[$p])
$min_dist= min($min_dist,$i-$p);
$p=$i;
}
}
if($min_dist==PHP_INT_MAX)
return-1;
return$min_dist;
}
$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);
?>
Javascript
<script>
functionminDist(arr , n , x , y)
{
vari=0,p=-1, min_dist=Number.MAX_VALUE;
for(i=0 ; i<n ; i++)
{
if(arr[i] ==x || arr[i] == y)
{
if(p != -1 && arr[i] != arr[p])
min_dist = Math.min(min_dist,i-p);
p=i;
}
}
if(min_dist==Number.MAX_VALUE)
return-1;
returnmin_dist;
}
vararr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3];
varn = arr.length;
varx = 3;
vary = 6;
document.write("Minimum distance between "+ x + " and "+ y
+ " is "+ minDist(arr, n, x, y));
</script>
Output
Minimum distance between 3 and 6 is 1
Complexity Analysis:
Time Complexity: O(n). Only one traversal of the array is needed.
Space Complexity: O(1). As no extra space is required.
Method 3:
Approach: The problem says that we want a minimum distance between
x and y. So the approach is traverse the array and while traversing in array if we got the number as x or y then we will store the difference between indices of previously found x or y and newly find x or y and like this for every time we will try to minimize the difference.
Traverse the array from i = 0 to i = n-1 where n is the size of
array.
While traversing if the current element is x then store index of current element in idx1 or if the current element is y then store index of current element in idx2.
If idx1 and idx2 variable are not equal to -1 then store minimum of min_dist, difference of idx1 and idx2 into ans.
At the end of traversal, if idx1 or idx2 are still -1(x or y not found in array) then return -1
or else return min_dist.
cout << "Minimum distance between "<< x << " and "<< y
<< " is "<< minDist(arr, n, x, y) << endl;
}
Java
publicclassGFG {
staticintminDist(intarr[], intn, intx, inty)
{
intidx1 = -1, idx2 = -1,
min_dist = Integer.MAX_VALUE;
for(inti = 0; i < n; i++) {
if(arr[i] == x) {
idx1 = i;
}
elseif(arr[i] == y) {
idx2 = i;
}
if(idx1 != -1&& idx2 != -1)
min_dist = Math.min(min_dist,
Math.abs(idx1 - idx2));
}
if(idx1 == -1|| idx2 == -1)
return-1;
else
returnmin_dist;
}
publicstaticvoidmain(String[] args)
{
intarr[] = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
intn = arr.length;
intx = 3;
inty = 6;
System.out.println("Minimum distance between "+ x
+ " and "+ y + " is "
+ minDist(arr, n, x, y));
}
}
Python3
importsys
defminDist(arr, n, x, y) :
idx1=-1; idx2=-1; min_dist =sys.maxsize;
fori inrange(n) :
ifarr[i]==x :
idx1=i
elifarr[i]==y :
idx2=i
ifidx1!=-1andidx2!=-1:
min_dist=min(min_dist,abs(idx1-idx2));
ifidx1==-1oridx2==-1:
return-1
else:
returnmin_dist
if__name__ =="__main__":
arr =[ 3, 5, 4, 2, 6, 5, 6, 6, 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)));
C#
usingSystem;
classMinimumDistance {
staticintminDist(int[]arr, intn,
intx, inty)
{
intidx1=-1,idx2=-1,min_dist = int.MaxValue;
for(inti=0;i<n;i++)
{
if(arr[i]==x)
{
idx1=i;
}
elseif(arr[i]==y)
{
idx2=i;
}
if(idx1!=-1 && idx2!=-1)
min_dist=Math.Min(min_dist,Math.Abs(idx1-idx2));
}
if(idx1==-1||idx2==-1)
return-1;
else
returnmin_dist;
}
publicstaticvoidMain()
{
int[]arr = { 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3};
intn = arr.Length;
intx = 3;
inty = 6;
Console.WriteLine("Minimum distance between "+ x + " and "+ y
+ " is "+ minDist(arr, n, x, y));
}
}
Javascript
<script>
functionminDist(arr , n , x , y)
{
varidx1=-1,idx2=-1,min_dist = Number.MAX_VALUE;
for(vari=0;i<n;i++)
{
if(arr[i]==x)
{
idx1=i;
}
elseif(arr[i]==y)
{
idx2=i;
}
if(idx1!=-1 && idx2!=-1)
min_dist=Math.min(min_dist,Math.abs(idx1-idx2));
}
if(idx1==-1||idx2==-1)
return-1;
else
returnmin_dist;
}
vararr = [ 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3];
varn = arr.length;
varx = 3;
vary = 6;
document.write("Minimum distance between "+ x + " and "+ y
+ " is "+ minDist(arr, n, x, y));
</script>
Output
Minimum distance between 3 and 6 is 4
Complexity Analysis:
Time
Complexity: O(n). Only one traversal of the array is required.
Space Complexity: O(1). No extra space is required.
Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem.
How do you find the minimum distance in Python?
To solve this, we will follow these steps:.
minimum := infinity..
for i in range 0 to size of nums, do. if nums[i] is same as target, then. if |i - start| < minimum, then. minimum := |i - start|.
return minimum..
How do you find the minimum distance between code words?
A code's minimum distance is the minimum of d(u,v) over all distinct codewords u and v. If the minimum distance is at least 2t + 1, a nearest neighbor decoder will always decode correctly when there are t or fewer errors.
How do you find the minimum distance in data structure?
Algorithm:.
Create a variable m = INT_MAX..
Run a nested loop, the outer loop runs from start to end (loop counter i), the inner loop runs from i+1 to end (loop counter j)..
If the ith element is x and jth element is y or vice versa, update m as m = min(m,j-i).