Minimize insertions in Array to make ratio of each pair as K
Last Updated :
21 Mar, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int find_min_additions(
int arr[], int n, int x)
{
unordered_map< int , int > m;
for ( int i = 0; i < n; i++) {
m[arr[i]]++;
}
sort(arr, arr + n);
int cnt_pairs = 0;
for ( int i = 0; i < n; ++i) {
if (m[arr[i] * x] > 0
&& m[arr[i]] > 0) {
m[arr[i] * x]--;
m[arr[i]]--;
cnt_pairs += 2;
}
}
return n - cnt_pairs;
}
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
import java.util.*;
class GFG{
static int find_min_additions(
int []arr, int n, int x)
{
HashMap<Integer, Integer> m = new HashMap<>();
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 );
}
Arrays.sort(arr);
int cnt_pairs = 0 ;
for ( int i = 0 ; i < n; ++i) {
if (m.containsKey(arr[i] * x) && m.get(arr[i] * x) > 0
&& m.get(arr[i]) > 0 ) {
m.put(arr[i] * x, m.get(arr[i] * x) - 1 );
m.put(arr[i], m.get(arr[i]) - 1 );
cnt_pairs += 2 ;
}
}
return n - cnt_pairs;
}
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));
}
}
|
Python3
def find_min_additions(arr, n, x):
m = {}
for i in range ( 0 , n):
m[arr[i]] = m[arr[i]] + 1 if arr[i] in m else 1
arr.sort()
cnt_pairs = 0
for i in range ( 0 , n):
if (arr[i] * x in m and arr[i] in m and m[arr[i] * x] > 0
and m[arr[i]] > 0 ):
m[arr[i] * x] - = 1
m[arr[i]] - = 1
cnt_pairs + = 2
return n - cnt_pairs
if __name__ = = "__main__" :
arr = [ 1 , 2 , 2 , 2 , 4 , 7 ]
n = len (arr)
K = 2
print (find_min_additions(arr, n, K))
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
static int find_min_additions(
int []arr, int n, int x)
{
Dictionary< int , int > m =
new Dictionary< int , int >();
for ( int i = 0; i < n; i++) {
int c = 0;
if (m.ContainsKey(arr[i])) {
c = m[arr[i]];
}
m[arr[i]] = c + 1;
}
Array.Sort(arr);
int cnt_pairs = 0;
for ( int i = 0; i < n; ++i) {
if (m.ContainsKey(arr[i] * x) && m[arr[i] * x] > 0
&& m[arr[i]] > 0) {
m[arr[i] * x]--;
m[arr[i]]--;
cnt_pairs += 2;
}
}
return n - cnt_pairs;
}
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));
}
}
|
Javascript
<script>
const find_min_additions = (arr, n, x) => {
let m = {};
for (let i = 0; i < n; i++) {
arr[i] in m ? m[arr[i]] += 1 : m[arr[i]] = 1;
}
arr.sort();
let cnt_pairs = 0;
for (let i = 0; i < n; ++i) {
if ((arr[i] * x) in m
&& arr[i] in m)
{
if (m[arr[i] * x] > 0 && m[arr[i]] > 0)
{
m[arr[i] * x] -= 1;
m[arr[i]] -= 1;
cnt_pairs += 2;
}
}
}
return n - cnt_pairs;
}
let arr = [1, 2, 2, 2, 4, 7];
let n = arr.length;
let K = 2;
document.write(find_min_additions(arr, n, K));
</script>
|
Time Complexity: O(N*log N) where N is the size of the array.
Space Complexity: O(N)
Another Approach:
- 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.
- Traverse the set s, and for each element i, check if its pair with ratio K*i is present in the map m.
- 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.
- 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:
- 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++
#include <bits/stdc++.h>
using namespace std;
int find_min_additions(
int arr[], int n, int x)
{
unordered_map< int , int > m;
set< int > s;
for ( int i = 0; i < n; i++) {
m[arr[i]]++;
s.insert(arr[i]);
}
int cnt_pairs = 0;
for ( auto i : s) {
if (m[i * x] > 0 && m[i] > 0) {
m[i * x]--;
m[i]--;
cnt_pairs += 2;
}
}
return n - cnt_pairs;
}
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
function find_min_additions(arr, n, x) {
const m = new Map();
const s = new Set();
for (let i = 0; i < n; i++) {
const num = arr[i];
m.set(num, (m.get(num) || 0) + 1);
s.add(num);
}
let cnt_pairs = 0;
for (let num of s) {
if (m.get(num * x) > 0 && m.get(num) > 0) {
m.set(num * x, m.get(num * x) - 1);
m.set(num, m.get(num) - 1);
cnt_pairs += 2;
}
}
return n - cnt_pairs;
}
const arr = [1, 2, 2, 2, 4, 7];
const n = arr.length;
const K = 2;
console.log(find_min_additions(arr, n, K));
|
C#
using System;
using System.Collections.Generic;
class GFG {
static int FindMinAdditions( int [] arr, int n, int x)
{
Dictionary< int , int > m = new Dictionary< int , int >();
HashSet< int > s = new HashSet< int >();
for ( int i = 0; i < n; i++) {
if (m.ContainsKey(arr[i]))
m[arr[i]]++;
else
m[arr[i]] = 1;
s.Add(arr[i]);
}
int cnt_pairs = 0;
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;
Console.WriteLine(FindMinAdditions(arr, n, K));
}
}
|
Java
import java.util.*;
public class GFG {
public static int findMinAdditions( int [] arr, int n, int x) {
HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
HashSet<Integer> s = new HashSet<Integer>();
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]);
}
int cntPairs = 0 ;
for ( int i : s) {
if (m.containsKey(i * x) && m.containsKey(i) && m.get(i * x) > 0 && m.get(i) > 0 ) {
m.put(i * x, m.get(i * x) - 1 );
m.put(i, m.get(i) - 1 );
cntPairs += 2 ;
}
}
return n - cntPairs;
}
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
from collections import defaultdict
def find_min_additions(arr, n, x):
m = defaultdict( int )
s = set ()
for i in range (n):
m[arr[i]] + = 1
s.add(arr[i])
cnt_pairs = 0
for i in s:
if m[i * x] > 0 and m[i] > 0 :
m[i * x] - = 1
m[i] - = 1
cnt_pairs + = 2
return n - cnt_pairs
arr = [ 1 , 2 , 2 , 2 , 4 , 7 ]
n = len (arr)
K = 2
print (find_min_additions(arr, n, K))
|
Time Complexity: O(N*logN)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...