Closest pair in an Array such that one number is multiple of the other

Given an array arr[] of integers of size N, the task is to find the closest pair in the given array such that one element is the multiple of the other. If no such pair exists then print -1.
Note: Closest pair means the difference between the index of any two elements must be minimum.
Examples:
Input: arr[] = {2, 3, 4, 5, 6}
Output: 2 4
Explanation:Â
The only possible pairs are (2, 4), (2, 6), (3, 6) out of which the pair which have minimum distance between them is (2, 4).ÂInput: arr[] = { 2, 3, 6, 4, 5 }
Output: 3 6
Explanation:Â
The only possible pairs are (2, 4), (2, 6), (3, 6) out of which the pair which have minimum distance between them is (3, 6).
Approach: The idea is to generate all possible pairs of the given array and check if there exists any pair of elements in the array if one element is the multiple of other and update the required minimum distance with the current pair. After the above operation print, the pair have the minimum distance among them and one is a multiple of the other. If no such pair exists then print -1.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include<bits/stdc++.h>using namespace std;  // Function to find the minimum// distance pair where one is the// multiple of the othervoid findPair(int a[], int n){    // Initialize the variables  int min_dist = INT_MAX;  int index_a = -1, index_b = -1;Â
  // Iterate for all the elements  for (int i = 0; i < n; i++)   {Â
    // Loop to make pairs    for (int j = i + 1; j < n; j++)    {        // Check if one is a        // multiple of other          // and have minimum distance        if ((a[i] % a[j] == 0 || a[j] % a[i] == 0) and j-i<min_dist)        {Â
          // Update the distance          min_dist = j - i;Â
          // Store indexes          index_a = i;          index_b = j;        }    }  }Â
  // If no such pair exists  if (index_a == -1)   {    cout << ("-1");  }Â
  // Print the answer  else  {    cout << "(" << a[index_a]        << ", " << a[index_b] << ")";  }}Â
// Driver Codeint main(){Â Â // Given array arr[]Â Â int a[] = { 2, 3, 4, 5, 6 };Â Â int n = sizeof(a)/sizeof(int);Â
  // Function Call  findPair(a, n);}Â
// This code is contributed by rock_cool |
Java
// Java program for the above approachimport java.util.*;class GFG {Â
    // Function to find the minimum    // distance pair where one is the    // multiple of the other    public static void    findPair(int a[], int n)    {Â
        // Initialize the variables        int min_dist = Integer.MAX_VALUE;        int index_a = -1, index_b = -1;Â
        // Iterate for all the elements        for (int i = 0; i < n; i++) {Â
            // Loop to make pairs            for (int j = i + 1; j < n; j++) {Â
                    // Check if one is a                    // multiple of other                    if ((a[i] % a[j] == 0                        || a[j] % a[i] == 0) && j-i<min_dist) {Â
                        // Update the distance                        min_dist = j - i;Â
                        // Store indexes                        index_a = i;                        index_b = j;                    }            }        }Â
        // If no such pair exists        if (index_a == -1) {            System.out.println("-1");        }Â
        // Print the answer        else {            System.out.print(                "(" + a[index_a]                + ", "                + a[index_b] + ")");        }    }Â
    // Driver Code    public static void        main(String[] args)    {        // Given array arr[]        int a[] = { 2, 3, 4, 5, 6 };        int n = a.length;Â
        // Function Call        findPair(a, n);    }} |
Python3
# Python3 program for the above approachimport sysÂ
# Function to find the minimum# distance pair where one is the# multiple of the otherdef findPair(a, n):Â
    # Initialize the variables    min_dist = sys.maxsize    index_a = -1    index_b = -1Â
    # Iterate for all the elements    for i in range(n):                 # Loop to make pairs        for j in range(i + 1, n): Â
          # Check if one is a          # multiple of other          if (((a[i] % a[j] == 0) or              (a[j] % a[i] == 0)) and j-i<min_dist):Â
            # Update the distance            min_dist = j - iÂ
            # Store indexes            index_a = i            index_b = jÂ
    # If no such pair exists    if (index_a == -1):        print("-1")Â
    # Print the answer    else:        print("(", a[index_a],             ", ", a[index_b], ")")Â
# Driver CodeÂ
# Given array arr[]a = [ 2, 3, 4, 5, 6 ]Â
n = len(a)Â
# Function callfindPair(a, n)Â
# This code is contributed by sanjoy_62 |
C#
// C# program for the above approachusing System;Â
class GFG{  // Function to find the minimum// distance pair where one is the// multiple of the otherpublic static void findPair(int []a, int n){         // Initialize the variables    int min_dist = int.MaxValue;    int index_a = -1, index_b = -1;Â
    // Iterate for all the elements    for(int i = 0; i < n; i++)    {                 // Loop to make pairs        for(int j = i + 1; j < n; j++)         {Â
            // Check if one is a            // multiple of other            if ((a[i] % a[j] == 0 ||                 a[j] % a[i] == 0) && j-i<min_dist)            {Â
              // Update the distance              min_dist = j - i;Â
              // Store indexes              index_a = i;              index_b = j;            }        }    }Â
    // If no such pair exists    if (index_a == -1)    {        Console.WriteLine("-1");    }Â
    // Print the answer    else    {        Console.Write("(" + a[index_a] +                     ", " + a[index_b] + ")");    }}Â
// Driver Codepublic static void Main(String[] args){         // Given array []arr    int []a = { 2, 3, 4, 5, 6 };         int n = a.Length;Â
    // Function Call    findPair(a, n);}}Â
// This code is contributed by 29AjayKumar |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find the minimum// distance pair where one is the// multiple of the otherfunction findPair(a, n){Â
    // Initialize the variables    let min_dist = Number.MAX_VALUE;    let index_a = -1, index_b = -1;         // Iterate for all the elements    for(let i = 0; i < n; i++)     {             // Loop to make pairs        for(let j = i + 1; j < n; j++)        {                                      // Check if one is a                // multiple of other                if ((a[i] % a[j] == 0 ||                    a[j] % a[i] == 0) && j-i<min_dist)                {                                 // Update the distance                min_dist = j - i;                                 // Store indexes                index_a = i;                index_b = j;                }        }    }         // If no such pair exists    if (index_a == -1)     {        document.write("-1");    }         // Print the answer    else    {        document.write("(" + a[index_a] +                       ", " + a[index_b] + ")");    }}Â
// Driver codeÂ
// Given array arr[]let a = [ 2, 3, 4, 5, 6 ];let n = a.length;Â
// Function CallfindPair(a, n);Â Â Â Â Â // This code is contributed by divyesh072019Â
</script> |
(2, 4)
Time Complexity: O(N2)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



