Java Program to Find the Minimum Distance between Array Elements

This is the Java Program to Find the Minimum Distance between Array Elements.

Problem Description

Given an array of n elements, and two integers say x and y, present in the array, find out the minimum distance between x and y in the array, that is the number of elements between x and y, including y. If the elements are not present print infinite value.

Example:
ArrayOne = [1, 2, 3, 4, 5, 6]
x = 2
y = 5
Output
3

Problem Solution

Check for the first occurrence of x or y in the array and store that index in a variable say z. Now continue traversing the array, if you find x or y, and it is not equal to the element at z, then update the minimum distance. Finally, update the index in variable z.

Program/Source Code

Here is the source code of the Java Program to Find the Minimum Distance between Array Elements. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.

  1.  
  2. // Java Program to Find the Minimum Distance between Array Elements
  3.  
  4. import java.io.BufferedReader;
  5. import java.io.InputStreamReader;
  6.  
  7. public class MinimumDistance {
  8.     // Function to calculate the minimum distance
  9.     static int minimumDistance(int[] array,int x,int y){
  10.         int prev,i=0;
  11.         prev = 0;
  12.         int dist = Integer.MAX_VALUE;
  13.         for(i=0; i<array.length; i++){
  14.             if(array[i] == x || array[i] == y){
  15.                 prev  = i;
  16.                 break;
  17.             }
  18.         }
  19.         for(i=prev+1; i<array.length; i++){
  20.             if(array[i] == x || array[i] == y){
  21.                 if(array[i] != array[prev] && (i-prev) < dist)
  22.                 {
  23.                     dist = i-prev;
  24.                     prev = i;
  25.                 }
  26.                 else{
  27.                     prev = i;
  28.                 }
  29.             }
  30.         }
  31.         return dist;
  32.     }
  33.     // Function to read  input and display the output
  34.     public static void main(String[] args) {
  35.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  36.         int size;
  37.         System.out.println("Enter the size of the array");
  38.         try {
  39.             size = Integer.parseInt(br.readLine());
  40.         } catch (Exception e) {
  41.             System.out.println("Invalid Input");
  42.             return;
  43.         }
  44.         int[] array = new int[size];
  45.         System.out.println("Enter array elements");
  46.         int i;
  47.         for (i = 0; i < array.length; i++) {
  48.             try {
  49.                 array[i] = Integer.parseInt(br.readLine());
  50.             } catch (Exception e) {
  51.                 System.out.println("An error Occurred");
  52.             }
  53.         }
  54.         int x,y;
  55.         System.out.println("Enter the numbers between which" + 
  56.                             " the distance is to be calculated");
  57.         try {
  58.             x = Integer.parseInt(br.readLine());
  59.             y = Integer.parseInt(br.readLine());
  60.         } catch (Exception e) {
  61.             System.out.println("Invalid Input");
  62.             return;
  63.         }
  64.         int output = minimumDistance(array,x,y);
  65.         System.out.println("The minimum distance is " + output);
  66.     }
  67. }
Program Explanation

1. In function minimumDistance(), the variable dist is initialized to Integer.MAX_VALUE.
2. The first loop for(i=0; i<array.length; i++) is used to find the first occurrence of either element x or y and store that index in variable prev.
3. The second loop for(i=prev+1; i<array.length; i++) traverses through the remaining part.
4. The conditions if(array[i] == x || array[i] == y) { if(array[i] != array[prev] && (i-prev) < dist), first checks for x or y.
5. When found it compares the element with the element at index prev. If they are not the same, then the dist is updated accordingly.

advertisement
advertisement

Time Complexity: O(n) where n is the number of elements in the array.

Runtime Test Cases
 
Case 1 (Positive Test Case):
 
Enter the size of the array
6
Enter array elements
1
2
3
4
5
6
Enter the numbers between which the distance is to be calculated
2
5
The minimum distance is 3
 
Case 2 (Negative Test Case):
 
Enter the size of the array
5
Enter array elements
9
8
7
6
5
Enter the numbers between which the distance is to be calculated
1
2
The minimum distance is 2147483647
 
Case 3 (Positive Test Case - another example):
 
Enter the size of the array
8
Enter array elements
12
2
45
57
7
54
3
2
Enter the numbers between which the distance is to be calculated
2
3
The minimum distance is 1

Sanfoundry Global Education & Learning Series – Java Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.