Find the value mapped to a given composite key for every query

Given three arrays firstkey[], secondkey[] and value[] where elements firstkey[i] and secondkey[i] denotes a composite key and their value is value[i], the task is to answer Q queries, each having two elements which denotes the composite key, whose corresponding value needs to be printed.Â
Examples:Â
Â
Input: firstkey[] = {4, 4, 5}Â
secondkey[] = {2, 1, 3}Â
value[] = {5, 3, 8}, Q = {(4, 1)}Â
Output: 3Â
Explanation:Â
The composite key is present at firstkey[1] (= 4) and secondkey[1] (= 1)Â
Therefore, the corresponding value is value[1] = 3
Input: firstkey[] = {3, 4, 3}Â
secondkey[] = {7, 1, 3}Â
value[] = {2, 3, 6}, Q = {(3, 3)}Â
Output: 6Â
Explanation:Â
The composite key is present at firstkey[2] (= 3) and secondkey[2] (= 3)Â
Therefore, the corresponding value is value[2] = 6Â
Â
Approach: The idea is to use map where the key of the map is a pair of two integers in C++, tuple in python denoting the respective elements of firstkey[] and secondkey[] which is mapped to the corresponding value[] element. This enables us to answer every query in the O(1) time.
For Example:Â
Â
Given arrays be -
firstkey[] = {4, 4, 5}
secondkey[] = {7, 1, 3}
value[] = {5, 3, 8}
Iterating over the Array, the map thus
formed is {(4, 7): 5, (4, 1): 3, (5, 3): 8}
Below is the implementation of the above approach:
Â
C++
// C++ implementation to find the// value of the given composite keysÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the composite// key value for multiple queriesvoid findCompositeKey(int firstkey[],                      int secondkey[], int value[], int n,                      vector<pair<int, int> > q){    // Map to store the composite    // key with a value    map<pair<int, int>, int> M;Â
    // Iterate over the arrays    // and generate the required    // mappings    for (int i = 0; i < n; i++) {        M.insert({ { firstkey[i], secondkey[i] },                   value[i] });    }Â
    // Loop to iterate over the    // elements of the queries    for (auto i : q) {Â
        // Condition to check if there        // is the composite key in map        if (M.find({ i.first,                     i.second })            != M.end()) {            cout << M[{ i.first, i.second }]                 << endl;        }        else {            cout << "Not Found" << endl;        }    }}Â
// Driver Codeint main(){    int firstkey[] = { 4, 4, 5 };    int secondkey[] = { 2, 1, 3 };    int value[] = { 5, 3, 8 };    int n = 3;    vector<pair<int, int> > q = { { 4, 1 },                                  { 5, 2 },                                  { 5, 3 } };Â
    findCompositeKey(firstkey, secondkey,                     value, n, q);    return 0;} |
Java
// Java implementation to find the// value of the given composite keysimport java.util.*;Â
class GFG{Â
static class Pair{Â Â Â Â int first, second;Â
    Pair(int first, int second)    {        this.first = first;        this.second = second;    }Â
    @Override    public boolean equals(Object obj)    {        if (obj == null)            return false;        if (!(obj instanceof Pair))            return false;        if (obj == this)            return true;                     return (this.first == ((Pair)obj).first) &&               (this.second == ((Pair)obj).second);    }Â
    @Override    public int hashCode()    {        return this.first + this.second;    }}Â
// Function to find the composite// key value for multiple queriesstatic void findCompositeKey(int firstkey[],                            int secondkey[],                             int value[], int n,                            int[][] q){         // Map to store the composite    // key with a value    Map<Pair, Integer> M = new HashMap<>();Â
    // Iterate over the arrays    // and generate the required    // mappings    for(int i = 0; i < n; i++)    {        M.put(new Pair(firstkey[i],                       secondkey[i]),                           value[i]);    }Â
    // Loop to iterate over the    // elements of the queries    for(int i = 0; i < q.length; i++)    {Â
        // Condition to check if there        // is the composite key in map        if (M.containsKey(new Pair(q[i][0],                                   q[i][1])))        {            System.out.println(M.get(new Pair(q[i][0],                                              q[i][1])));        }        else        {            System.out.println("Not Found");        }    }}Â
// Driver codepublic static void main(String[] args){    int firstkey[] = { 4, 4, 5 };    int secondkey[] = { 2, 1, 3 };    int value[] = { 5, 3, 8 };    int n = 3;         int[][] q = { { 4, 1 },                  { 5, 2 },                  { 5, 3 } };Â
    findCompositeKey(firstkey, secondkey,                     value, n, q);}}Â
// This code is contributed by offbeat |
Python3
# Python implementation to find the# value of the given composite keysÂ
# Function to find the composite# key value for multiple queriesdef findCompositeKey(firstkey, secondkey, value, n, q):    # Map to store the composite    # key with a value    M = {}Â
    # Iterate over the arrays    # and generate the required    # mappings    for i in range(n):        M[(firstkey[i], secondkey[i])] = value[i]Â
    # Loop to iterate over the    # elements of the queries    for i in q:        # Condition to check if there        # is the composite key in map        if (i[0], i[1]) in M:            print(M[(i[0], i[1])])        else:            print("Not Found")Â
Â
# Driver Codeif __name__ == '__main__':Â Â Â Â firstkey = [4, 4, 5]Â Â Â Â secondkey = [2, 1, 3]Â Â Â Â value = [5, 3, 8]Â Â Â Â n = 3Â Â Â Â q = [(4, 1), (5, 2), (5, 3)]Â
    findCompositeKey(firstkey, secondkey,                     value, n, q)     # This code is contributed by offbeat |
C#
// C# implementation to find the// value of the given composite keysusing System;using System.Collections.Generic;Â
class Program{Â
  // Function to find the composite key value for multiple  // queries  static void FindCompositeKey(int[] firstkey,                               int[] secondkey,                               int[] value, int n,                               List<Tuple<int, int> > q)  {    // Map to store the composite key with a value    Dictionary<Tuple<int, int>, int> M      = new Dictionary<Tuple<int, int>, int>();Â
    // Iterate over the arrays and generate the required    // mappings    for (int i = 0; i < n; i++) {      M.Add(Tuple.Create(firstkey[i], secondkey[i]),            value[i]);    }Â
    // Loop to iterate over the elements of the queries    foreach(var i in q)    {      // Condition to check if there is the composite      // key in map      if (M.ContainsKey(        Tuple.Create(i.Item1, i.Item2))) {        Console.WriteLine(          M[Tuple.Create(i.Item1, i.Item2)]);      }      else {        Console.WriteLine("Not Found");      }    }  }Â
  // Driver Code  static void Main(string[] args)  {    int[] firstkey = { 4, 4, 5 };    int[] secondkey = { 2, 1, 3 };    int[] value = { 5, 3, 8 };    int n = 3;    List<Tuple<int, int> > q      = new List<Tuple<int, int> >{      Tuple.Create(4, 1), Tuple.Create(5, 2),      Tuple.Create(5, 3)      };Â
    FindCompositeKey(firstkey, secondkey, value, n, q);    Console.ReadLine();  }}Â
// This code is contributed by rutikbhosale |
Javascript
// JavaScript implementation to find the// value of the given composite keysÂ
// Function to find the composite// key value for multiple queriesfunction findCompositeKey(firstkey, secondkey, value, n, q) {  // Map to store the composite  // key with a value  const M = new Map();Â
  // Iterate over the arrays  // and generate the required  // mappings  for (let i = 0; i < n; i++) {    M.set(`${firstkey[i]}_${secondkey[i]}`, value[i]);  }Â
  // Loop to iterate over the  // elements of the queries  for (let i of q) {Â
    // Condition to check if there    // is the composite key in map    if (M.has(`${i[0]}_${i[1]}`)) {      console.log(M.get(`${i[0]}_${i[1]}`));    }    else {      console.log("Not Found");    }  }}Â
// Driver Codeconst firstkey = [4, 4, 5];const secondkey = [2, 1, 3];const value = [5, 3, 8];const n = 3;const q = [[4, 1], [5, 2], [5, 3]];Â
findCompositeKey(firstkey, secondkey, value, n, q); |
3 Not Found 8
Â
Time Complexity: O(nlogn)
Auxiliary Space: O(n) because using map
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



