Skip to content
Related Articles

Related Articles

Minimize insertions in Array to make ratio of each pair as K

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Mar, 2022
View Discussion
Improve Article
Save Article

Given an array arr[] of length N the task is to find the minimum number of elements to be added in the array such that there exists every independent pair in the array whose ratio is K.

Examples: 

Input: arr[] = {1, 2, 2, 2, 4, 7}, K = 2
Output: 2
Explanation: 4, 14 can be added to make the array as {1, 2, 2, 2, 4, 7, 4, 14}
Therefore if we make independent pairs as {1, 2}, {2, 4}, {2, 4}, and {7, 14}, the ratio of each is K (=2).

Input: arr[] = {5, 2, 3, 5, 15}, K = 3
Output: 3

 

Approach: The above problem can be solved using greedy and hashing technique, based on below observation:

Since it is given that the ratio of the pairs should be K,  

If the two elements be made as pair with ratio K are a and b, then
    => a/b = K
    => a = b*K
    => The two elements will be always b and b*K

Therefore, for the ratio of a and b to be K, b and b*K should be present in the array. 

So in the Array, for every element arr[i],

  • we need check if arr[i] * K is present in that array.
  • If it is present, make it a pair
  • Else add the arr[i] * K to the array

Follow these steps to solve the above problem:

  • Initialize a hashmap m to store the frequencies of the elements in the array.
  • Traverse the array and store the frequencies
  • Sort the array arr[].
  • Initialize the cnt_pairs to store the count of the available pairs with the ration k.
  • Traverse through the sorted array and check for the pairing element.
  • Check if the pair with ratio k is present for arr[i], consider them as a pair and remove them from the hashmap by decreasing the frequencies.
  • Keep track of available pairs in the cnt_pairs variable by incrementing it by 2.
  • Print the single elements by subtracting cnt_pairs from the n.

Below is the implementation of the above approach:

C++




// C++ program to minimize insertions in
// Array to make ratio of each pair as K
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to minimize insertions
// in Array to make ratio
// of each pair as K
int find_min_additions(
    int arr[], int n, int x)
{
    // Initialize a hashmap
    // and store the frequencies
    // of the array elements
    unordered_map<int, int> m;
 
    // Traverse the array
    // and store the frequencies
    for (int i = 0; i < n; i++) {
        m[arr[i]]++;
    }
 
    // sort the array
    sort(arr, arr + n);
 
    // Initialize the cnt_pairs to store the
    // count of the available pairs
    int cnt_pairs = 0;
 
    for (int i = 0; i < n; ++i) {
 
        // Check if the pair with ratio k is
        // present for arr[i]
        if (m[arr[i] * x] > 0
            && m[arr[i]] > 0) {
 
            // Consider them as a pair
            // and remove from the hashmap
            m[arr[i] * x]--;
            m[arr[i]]--;
 
            // Add the count of the pairs
            cnt_pairs += 2;
        }
    }
 
    // Return the count of single elements
    // that need another element
    // to make ratio k
    return n - cnt_pairs;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 2, 2, 4, 7 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
 
    cout << find_min_additions(arr, n, K);
}

Java




// Java program to minimize insertions in
// Array to make ratio of each pair as K
import java.util.*;
 
class GFG{
 
  // Function to minimize insertions
  // in Array to make ratio
  // of each pair as K
  static int find_min_additions(
    int []arr, int n, int x)
  {
 
    // Initialize a hashmap
    // and store the frequencies
    // of the array elements
    HashMap<Integer, Integer> m = new HashMap<>();
 
 
    // Traverse the array
    // and store the frequencies
    for (int i = 0; i < n; i++) {
      int c = 0;
      if(m.containsKey(arr[i])) {
        c = m.get(arr[i]);
      }
      m.put(arr[i], c + 1);
    }
 
    // sort the array
    Arrays.sort(arr);
 
    // Initialize the cnt_pairs to store the
    // count of the available pairs
    int cnt_pairs = 0;
 
    for (int i = 0; i < n; ++i) {
 
      // Check if the pair with ratio k is
      // present for arr[i]
      if (m.containsKey(arr[i] * x) && m.get(arr[i] * x) > 0
          && m.get(arr[i]) > 0) {
 
        // Consider them as a pair
        // and remove from the hashmap
        m.put(arr[i] * x, m.get(arr[i] * x) - 1);
        m.put(arr[i], m.get(arr[i]) - 1);
 
        // Add the count of the pairs
        cnt_pairs += 2;
      }
    }
 
    // Return the count of single elements
    // that need another element
    // to make ratio k
    return n - cnt_pairs;
  }
 
  // Driver code
  public static void main (String[] args) {
    int arr[] = { 1, 2, 2, 2, 4, 7 };
    int n = arr.length;
    int K = 2;
 
    System.out.print(find_min_additions(arr, n, K));
  }
}
 
// This code is contributed by hrithikgarg03188.

Python3




# Python program to minimize insertions in
# Array to make ratio of each pair as K
 
# Function to minimize insertions
# in Array to make ratio
# of each pair as K
def find_min_additions(arr, n,  x):
 
    # Initialize a hashmap
    # and store the frequencies
    # of the array elements
    m = {}
 
    # Traverse the array
    # and store the frequencies
    for i in range(0, n):
        m[arr[i]] = m[arr[i]] + 1 if arr[i] in m else 1
 
    # sort the array
    arr.sort()
 
    # Initialize the cnt_pairs to store the
    # count of the available pairs
    cnt_pairs = 0
 
    for i in range(0, n):
 
        # Check if the pair with ratio k is
        # present for arr[i]
        if (arr[i] * x in m and arr[i] in m and m[arr[i] * x] > 0
                and m[arr[i]] > 0):
 
            # Consider them as a pair
            # and remove from the hashmap
            m[arr[i] * x] -= 1
            m[arr[i]] -= 1
 
            # Add the count of the pairs
            cnt_pairs += 2
 
    # Return the count of single elements
    # that need another element
    # to make ratio k
    return n - cnt_pairs
 
# Driver code
if __name__ == "__main__":
 
    arr = [1, 2, 2, 2, 4, 7]
    n = len(arr)
    K = 2
 
    print(find_min_additions(arr, n, K))
 
# This code is contributed by rakeshsahni

C#




// C# program to minimize insertions in
// Array to make ratio of each pair as K
 
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to minimize insertions
  // in Array to make ratio
  // of each pair as K
  static int find_min_additions(
    int []arr, int n, int x)
  {
 
    // Initialize a hashmap
    // and store the frequencies
    // of the array elements
    Dictionary<int, int> m = 
      new Dictionary<int, int>();
 
    // Traverse the array
    // and store the frequencies
    for (int i = 0; i < n; i++) {
      int c = 0;
      if(m.ContainsKey(arr[i])) {
        c = m[arr[i]];
      }
      m[arr[i]] = c + 1;
    }
 
    // sort the array
    Array.Sort(arr);
 
    // Initialize the cnt_pairs to store the
    // count of the available pairs
    int cnt_pairs = 0;
 
    for (int i = 0; i < n; ++i) {
 
      // Check if the pair with ratio k is
      // present for arr[i]
      if (m.ContainsKey(arr[i] * x) && m[arr[i] * x] > 0
          && m[arr[i]] > 0) {
 
        // Consider them as a pair
        // and remove from the hashmap
        m[arr[i] * x]--;
        m[arr[i]]--;
 
        // Add the count of the pairs
        cnt_pairs += 2;
      }
    }
 
    // Return the count of single elements
    // that need another element
    // to make ratio k
    return n - cnt_pairs;
  }
 
  // Driver code
  public static void Main()
  {
    int []arr = { 1, 2, 2, 2, 4, 7 };
    int n = arr.Length;
    int K = 2;
 
    Console.Write(find_min_additions(arr, n, K));
  }
}
 
// This code is contributed by Samim Hossain Mondal.

Javascript




<script>
    // JavaScript program to minimize insertions in
    // Array to make ratio of each pair as K
 
    // Function to minimize insertions
    // in Array to make ratio
    // of each pair as K
    const find_min_additions = (arr, n, x) => {
     
        // Initialize a hashmap
        // and store the frequencies
        // of the array elements
        let m = {};
 
        // Traverse the array
        // and store the frequencies
        for (let i = 0; i < n; i++) {
            arr[i] in m ? m[arr[i]] += 1 : m[arr[i]] = 1;
        }
 
        // sort the array
        arr.sort();
 
        // Initialize the cnt_pairs to store the
        // count of the available pairs
        let cnt_pairs = 0;
 
        for (let i = 0; i < n; ++i) {
 
            // Check if the pair with ratio k is
            // present for arr[i]
            if ((arr[i] * x) in m
                && arr[i] in m)
            {
                if (m[arr[i] * x] > 0 && m[arr[i]] > 0)
                {
                 
                    // Consider them as a pair
                    // and remove from the hashmap
                    m[arr[i] * x] -= 1;
                    m[arr[i]] -= 1;
 
                    // Add the count of the pairs
                    cnt_pairs += 2;
                }
            }
        }
 
        // Return the count of single elements
        // that need another element
        // to make ratio k
 
        return n - cnt_pairs;
    }
 
    // Driver code
 
    let arr = [1, 2, 2, 2, 4, 7];
    let n = arr.length;
    let K = 2;
 
    document.write(find_min_additions(arr, n, K));
 
//  This code is contributed by rakeshsahni
 
</script>

 
 

Output

2

 

Time Complexity: O(N*log N) where N is the size of the array.
Space Complexity: O(N) 

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!