Open In App

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

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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) 

Another Approach:

  1. Initialize an unordered_map m and a set s.                                                                                                                                                                           (a) m will store the frequencies of each element in the array.
    (b) s will store the unique elements in the array.
    (c) Traverse the array and store the frequencies of each element in the map m.
  2. Traverse the set s, and for each element i, check if its pair with ratio K*i is present in the map m.
  3. If the pair exists, decrement the frequencies of both elements in the map.
    (a) Increment the cnt_pairs by 2, as two elements make a pair.
  4. Return the count of elements that were not part of a pair, which is equal to the total number of elements minus the cnt_pairs.In the main function:
  5. Initialize an array and its size.
    Call the function find_min_additions() with the array, size, and a given value of K as arguments.
    Print the output.

 Below is the implementation of 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;
// Initialize a set to store
// the unique elements in the array
set<int> s;
 
// Traverse the array
// and store the frequencies
for (int i = 0; i < n; i++) {
    m[arr[i]]++;
    s.insert(arr[i]);
}
 
// Initialize the cnt_pairs to store the
// count of the available pairs
int cnt_pairs = 0;
 
// Traverse through the set and check
// for the pairing element
for (auto i : s) {
 
    // Check if the pair with ratio k is
    // present for i
    if (m[i * x] > 0 && m[i] > 0) {
 
        // Consider them as a pair
        // and remove from the hashmap
        m[i * x]--;
        m[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);
}


Javascript




// 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
function find_min_additions(arr, n, x) {
  // Initialize a hashmap
  // and store the frequencies
  // of the array elements
  const m = new Map();
  // Initialize a set to store
  // the unique elements in the array
  const s = new Set();
 
  // Traverse the array
  // and store the frequencies
  for (let i = 0; i < n; i++) {
    const num = arr[i];
    m.set(num, (m.get(num) || 0) + 1);
    s.add(num);
  }
 
  // Initialize the cnt_pairs to store the
  // count of the available pairs
  let cnt_pairs = 0;
 
  // Traverse through the set and check
  // for the pairing element
  for (let num of s) {
 
    // Check if the pair with ratio k is
    // present for i
    if (m.get(num * x) > 0 && m.get(num) > 0) {
 
      // Consider them as a pair
      // and remove from the hashmap
      m.set(num * x, m.get(num * x) - 1);
      m.set(num, m.get(num) - 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
const arr = [1, 2, 2, 2, 4, 7];
const n = arr.length;
const K = 2;
console.log(find_min_additions(arr, n, K));
 
// THIS CODE IS CONTRIBUTED BY CHANDAN AGARWAL


C#




// C# program to minimize insertions in
// Array to make ratio of each pair as K
 
using System;
using System.Collections.Generic;
 
class GFG {
    // Function to minimize insertions
    // in Array to make ratio
    // of each pair as K
    static int FindMinAdditions(int[] arr, int n, int x)
    {
        // Initialize a dictionary
        // and store the frequencies
        // of the array elements
        Dictionary<int, int> m = new Dictionary<int, int>();
 
        // Initialize a set to store
        // the unique elements in the array
        HashSet<int> s = new HashSet<int>();
 
        // Traverse the array
        // and store the frequencies
        for (int i = 0; i < n; i++) {
            // Check if the pair with ratio k is
            // present for i
            if (m.ContainsKey(arr[i]))
                m[arr[i]]++;
            else
                m[arr[i]] = 1;
 
            s.Add(arr[i]);
        }
 
        // Initialize the cnt_pairs to store the
        // count of the available pairs
        int cnt_pairs = 0;
 
        // Traverse through the set and check
        // for the pairing element
        foreach(int i in s)
        {
            if (m.ContainsKey(i * x) && m[i * x] > 0
                && m[i] > 0) {
                m[i * x]--;
                m[i]--;
                cnt_pairs += 2;
            }
        }
 
        return n - cnt_pairs;
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 1, 2, 2, 2, 4, 7 };
        int n = arr.Length;
        int K = 2;
 
        // Function Call
        Console.WriteLine(FindMinAdditions(arr, n, K));
    }
}


Java




// Java program to minimize insertions in
// Array to make ratio of each pair as K
 
import java.util.*;
 
public class GFG {
    // Function to minimize insertions
    // in Array to make ratio
    // of each pair as K
    public static int findMinAdditions(int[] arr, int n, int x) {
        // Initialize a hashmap
        // and store the frequencies
        // of the array elements
        HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
        // Initialize a set to store
        // the unique elements in the array
        HashSet<Integer> s = new HashSet<Integer>();
 
        // Traverse the array
        // and store the frequencies
        for (int i = 0; i < n; i++) {
            if (m.containsKey(arr[i])) {
                m.put(arr[i], m.get(arr[i]) + 1);
            } else {
                m.put(arr[i], 1);
            }
            s.add(arr[i]);
        }
 
        // Initialize the cnt_pairs to store the
        // count of the available pairs
        int cntPairs = 0;
 
        // Traverse through the set and check
        // for the pairing element
        for (int i : s) {
            // Check if the pair with ratio k is
            // present for i
            if (m.containsKey(i * x) && m.containsKey(i) && m.get(i * x) > 0 && m.get(i) > 0) {
                // Consider them as a pair
                // and remove from the hashmap
                m.put(i * x, m.get(i * x) - 1);
                m.put(i, m.get(i) - 1);
 
                // Add the count of the pairs
                cntPairs += 2;
            }
        }
 
        // Return the count of single elements
        // that need another element
        // to make ratio k
        return n - cntPairs;
    }
 
    // 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.println(findMinAdditions(arr, n, k));
    }
}


Python3




# Python3 program to minimize insertions in
# Array to make ratio of each pair as K
 
# Python program to minimize insertions in
# Array to make ratio of each pair as K
 
from collections import defaultdict
 
# Function to minimize insertions
# in Array to make ratio
# of each pair as K
def find_min_additions(arr, n, x):
    # Initialize a dictionary
    # and store the frequencies
    # of the array elements
    m = defaultdict(int)
    # Initialize a set to store
    # the unique elements in the array
    s = set()
 
    # Traverse the array
    # and store the frequencies
    for i in range(n):
        m[arr[i]] += 1
        s.add(arr[i])
 
    # Initialize the cnt_pairs to store the
    # count of the available pairs
    cnt_pairs = 0
 
    # Traverse through the set and check
    # for the pairing element
    for i in s:
        # Check if the pair with ratio k is
        # present for i
        if m[i * x] > 0 and m[i] > 0:
            # Consider them as a pair
            # and remove from the dictionary
            m[i * x] -= 1
            m[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
arr = [1, 2, 2, 2, 4, 7]
n = len(arr)
K = 2
print(find_min_additions(arr, n, K))


Output

2

Time Complexity: O(N*logN)

Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads