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[].
Example
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
# 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))
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 previous 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)));
'Python' 카테고리의 다른 글
[python] Union and Intersection of two sorted arrays (0) | 2021.09.15 |
---|---|
[python] Longest Span with same Sum in two Binary arrays (0) | 2021.09.15 |