Open In App

Find Z for adding K elements of A to match K elements of B

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two arrays A and B of the same length and an integer K (K ≥ 1). Then the task is to return all possible values of Z (Z > 0), such that adding it in any K number of elements of A gives K elements of B. If no value of Z is possible print Not Possible.

Examples:

Input: A[] = { 3, 1, 5, 7 }, B[] = { 1, 4, 3, 6 }, K = 2
Output: 1 3
Explanation: For the value of K = 2, There are two possible values of Z:

  • Z = 1:
    • Add 1 in A1 = 3 and A3 = 5, Which gives 3 + 1 = 4 and 5 + 1 = 6 respectively, Which are equal to B2 and B4 respectively.    
  • Z = 3: 
    • Add 3 in A1 = 3 and A2 = 1, Which gives 3 + 3 = 6 and  1 + 3 = 4 respectively, Which are equal to B4 and B2 respectively.

These are possible values of Z, Which are capable of making exactly 2 elements of A[] equal to 2 elements of B[].  

Input: A[] = { 1, 4, 9, 5 }, B[] = { 1, 1, 3, 4 }, K = 3
Output: Not Possible
Explanation: It can be verified that there exists no such of value Z, Which can make any 3 elements of A[] equal to any 3 elements of B[]. 

Approach: Implement the idea below to solve the problem

The problem is observation based and can be solved by using the HashMap data structure. For more clarification see the Concept of approach section below. 

Concept of Approach: 

  • According to the problem statement, We come to know that, We have to add an integer Z (Z > 0), such that adding it in K elements of A[] gives K elements of B[]. Then for K elements of A[] there should exist an integer Z such that X + Z = Y (where X is any one element of A[] and Y is any one element of B[]).
  • So, the observation comes that if (Y – X) = Z and the frequency of any Z in HashMap is equal to K, Then that value of (Y – X) is valid for Z else not.

Steps were taken to solve the problem:

  • Create a HashMap let’s say map.
  • Run two loop, outer loop from i = 0 to i < B.length and inner loop from j = 0 to j < A.length():
    • Update the map with the frequency of differences. Formally, (B[ i ] – A[ j ]), If and only if (B[ i ] – A[ j ]) > 0.
  • Create an ArrayList let’s say list storing possible values of Z.
  • Traverse over the map using a loop and update list that difference value(s), which has a frequency equal to K.
  • Output all the possible values of Z.       

Below is the code to implement the approach:

C++

// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to find the value of Z
void valueOfZ(int A[], int B[], int K, int n1, int n2)
{
    // HashMap initialized for counting
    // the frequency of differences
    map<int, int> mp;

    // Nested Loops for calculate differences
    for (int i = 0; i < n2; i++) {
        for (int j = 0; j < n1; j++) {
            if ((B[i] - A[j]) > 0) {
                mp[B[i] - A[j]]++;
            }
        }
    }

    // Vector for holding possible value(s) of Z
    vector<int> Z;

    // Loop for traversing over Map
    for (auto it : mp) {

        // If any value of difference
        // found such that It has
        // frequency equal to K Then
        // updating vector Z with
        // that difference value
        if (it.second >= K) {
            Z.push_back(it.first);
        }
    }

    // Printing the value of Z
    if (Z.empty()) {
        cout << "Not Possible";
    }
    else {
        for (auto i : Z) {
            cout << i << " ";
        }
    }
}

// Driver code
int main()
{
    // Input Arrays
    int K = 2;
    int A[] = { 3, 1, 5, 7 };
    int B[] = { 1, 4, 3, 6 };
    int n1 = sizeof(A) / sizeof(A[0]);
    int n2 = sizeof(B) / sizeof(B[0]);

    // Function call
    valueOfZ(A, B, K, n1, n2);

    return 0;
}

Java

// Java code to implement the approach
import java.io.*;
import java.lang.*;
import java.util.*;

class Main {

    // Driver Function
    public static void main(String[] args)
        throws java.lang.Exception
    {

        // Input Arrays
        int K = 2;
        int A[] = { 3, 1, 5, 7 };
        int B[] = { 1, 4, 3, 6 };

        // Function call
        ValueOfZ(A, B, K);
    }

    // Method for finding the value of Z
    static void ValueOfZ(int[] A, int[] B, int K)
    {

        // HashMap initialized for counting
        // the frequency of differences
        HashMap<Integer, Integer> map = new HashMap<>();

        // Nested Loops for
        // calculate differences
        for (int i = 0; i < (B.length); i++) {
            for (int j = 0; j < A.length; j++) {
                if ((B[i] - A[j]) > 0) {
                    map.put((B[i] - A[j]),
                            map.get((B[i] - A[j])) == null
                                ? 1
                                : map.get((B[i] - A[j]))
                                      + 1);
                }
            }
        }

        // ArrayList for holding possible
        // value(s) of Z
        ArrayList<Integer> Z = new ArrayList<>();

        // Loop for traversing over Map
        for (Map.Entry<Integer, Integer> set :
             map.entrySet()) {

            // If any value of difference
            // found such that It has
            // frequency equal to K Then
            // updating ArrayList Z with
            // that difference value
            if (set.getValue() >= K) {
                Z.add((int)set.getKey());
            }
        }

        // Printing the value of Z
        System.out.println(Z.isEmpty() ? "Not Possible"
                                       : " " + Z);
    }
}

Python

# Python code to implement the approach
from collections import defaultdict

# Method for finding the value of Z
def ValueOfZ(A, B, K):
    # Dictionary initialized for counting
    # the frequency of differences
    freq = defaultdict(int)

    # Nested Loops for
    # calculate differences
    for i in range(len(B)):
        for j in range(len(A)):
            if (B[i] - A[j]) > 0:
                freq[(B[i] - A[j])] += 1

    # List for holding possible
    # value(s) of Z
    Z = []

    # Loop for traversing over dictionary
    for key, value in freq.items():
        # If any value of difference
        # found such that It has
        # frequency equal to K Then
        # updating List Z with
        # that difference value
        if value >= K:
            Z.append(key)

    # Printing the value of Z
    if not Z:
        print("Not Possible")
    else:
        print(Z)

# Driver Function
if __name__ == '__main__':
    # Input Arrays
    K = 2
    A = [3, 1, 5, 7]
    B = [1, 4, 3, 6]

    # Function call
    ValueOfZ(A, B, K)

Javascript

// JavaScript code to implement the approach

// Driver Function
function main() {
    // Input Arrays
    let K = 2;
    let A = [3, 1, 5, 7];
    let B = [1, 4, 3, 6];

    // Function call
    ValueOfZ(A, B, K);
}

// Method for finding the value of Z
function ValueOfZ(A, B, K) {
    // HashMap initialized for counting
    // the frequency of differences
    let map = new Map();

    // Nested Loops for
    // calculate differences
    for (let i = 0; i < B.length; i++) {
        for (let j = 0; j < A.length; j++) {
            if ((B[i] - A[j]) > 0) {
                map.set(B[i] - A[j], (map.get(B[i] - A[j]) == null) ? 1 : map.get(B[i] - A[j]) + 1);
            }
        }
    }

    // ArrayList for holding possible
    // value(s) of Z
    let Z = [];

    // Loop for traversing over Map
    for (let [key, value] of map.entries()) {

        // If any value of difference
        // found such that It has
        // frequency equal to K Then
        // updating ArrayList Z with
        // that difference value
        if (value >= K) {
            Z.push(key);
        }
    }

    // Printing the value of Z
    console.log((Z.length === 0) ? "Not Possible" : " " + Z);
}

// calling the main function
main();

// This code is generated by Chetan Bargal.

C#

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        // Input Arrays
        int[] A = new int[] { 3, 1, 5, 7 };
        int[] B = new int[] { 1, 4, 3, 6 };
        int K = 2;

        // Function call
        ValueOfZ(A, B, K);
    }

    // Method for finding the value of Z
    static void ValueOfZ(int[] A, int[] B, int K)
    {
        // Dictionary initialized for counting
        // the frequency of differences
        Dictionary<int, int> freq = new Dictionary<int, int>();

        // Nested Loops for
        // calculate differences
        for (int i = 0; i < B.Length; i++)
        {
            for (int j = 0; j < A.Length; j++)
            {
                if ((B[i] - A[j]) > 0)
                {
                    if (!freq.ContainsKey(B[i] - A[j]))
                    {
                        freq.Add(B[i] - A[j], 0);
                    }
                    freq[B[i] - A[j]]++;
                }
            }
        }

        // List for holding possible
        // value(s) of Z
        List<int> Z = new List<int>();

        // Loop for traversing over dictionary
        foreach (KeyValuePair<int, int> kvp in freq)
        {
            // If any value of difference
            // found such that It has
            // frequency equal to K Then
            // updating List Z with
            // that difference value
            if (kvp.Value >= K)
            {
                Z.Add(kvp.Key);
            }
        }

        // Printing the value of Z
        if (Z.Count == 0)
        {
            Console.WriteLine("Not Possible");
        }
        else
        {
            Console.WriteLine(string.Join(", ", Z));
        }
    }
}
Output

 [1, 3]

Time Complexity: O(N2), Where N is the length of array A
Auxiliary Space: O(2 * N)  = O(N), As HashMap is used to store the difference between elements of A[] and B[].



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads