Nuts & Bolts Problem (Lock & Key problem) | Set 2 (Hashmap) - GeeksforGeeks

23 Jun, 2021
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one is bigger/smaller.Examples: 
Input : nuts[] = {'@', '#', '$', '%', '^', '&'}
        bolts[] = {'$', '%', '&', '^', '@', '#'}
Output : Matched nuts and bolts are-
        $ % & ^ @ # 
        $ % & ^ @ #  
Another way of asking this problem is, given a box with locks and keys where one lock can be opened by one key in the box. We need to match the pair.
We have discussed a sorting based solution below post.Nuts & Bolts Problem (Lock & Key problem) | Set 1In this post, hashmap based approach is discussed. 
Traverse the nuts array and create a hashmapTraverse the bolts array and search for it in hashmap.If it is found in the hashmap of nuts then this means bolts exist for that nut.
Traverse the nuts array and create a hashmap
Traverse the bolts array and search for it in hashmap.
If it is found in the hashmap of nuts then this means bolts exist for that nut.
C++
Java
Python3
C#
Javascript
// Hashmap based solution to solve#include <bits/stdc++.h>using namespace std; // function to match nuts and boltsvoid nutboltmatch(char nuts[], char bolts[], int n){    unordered_map<char, int> hash;     // creating a hashmap for nuts    for (int i = 0; i < n; i++)        hash[nuts[i]] = i;     // searching for nuts for each bolt in hash map    for (int i = 0; i < n; i++)        if (hash.find(bolts[i]) != hash.end())            nuts[i] = bolts[i];     // print the result    cout << "matched nuts and bolts are-" << endl;    for (int i = 0; i < n; i++)        cout << nuts[i] << " ";    cout << endl;    for (int i = 0; i < n; i++)        cout << bolts[i] << " ";} // Driver codeint main(){    char nuts[] = {'@', '#', '$', '%', '^', '&'};    char bolts[] = {'$', '%', '&', '^', '@', '#'};    int n = sizeof(nuts) / sizeof(nuts[0]);    nutboltmatch(nuts, bolts, n);    return 0;}
// Hashmap based solution to solveimport java.util.HashMap;class GFG{   // function to match nuts and bolts  static void nutboltmatch(char nuts[], char bolts[], int n)  {    HashMap<Character, Integer> hash = new HashMap<>();     // creating a hashmap for nuts    for (int i = 0; i < n; i++)      hash.put(nuts[i], i);     // searching for nuts for each bolt in hash map    for (int i = 0; i < n; i++)      if (hash.containsKey(bolts[i]))        nuts[i] = bolts[i];     // print the result    System.out.println("matched nuts and bolts are-");    for (int i = 0; i < n; i++)      System.out.print(nuts[i] + " ");    System.out.println();    for (int i = 0; i < n; i++)      System.out.print(bolts[i] + " ");  }   // Driver code  public static void main(String[] args)  {    char nuts[] = { '@', '#', '$', '%', '^', '&' };    char bolts[] = { '$', '%', '&', '^', '@', '#' };    int n = nuts.length;    nutboltmatch(nuts, bolts, n);  }} // This code is contributed by sanjeev2552
# Python3 program to implement# above approach# Hashmap based solution to# solve # Function to match nuts and# boltsdef nutboltmatch(nuts,                 bolts, n):     hash1 = {}     # creating a hashmap    # for nuts    for i in range(n):        hash1[nuts[i]] = i     # searching for nuts for    # each bolt in hash map    for i in range(n):        if (bolts[i] in hash1):            nuts[i] = bolts[i]     # Print the result    print("matched nuts and bolts are-")    for i in range(n):        print(nuts[i],              end = " ")    print()    for i in range(n):        print(bolts[i],              end = " ") # Driver codeif __name__ == "__main__":     nuts = ['@', '#', '$',            '%', '^', '&']    bolts = ['$', '%', '&',             '^', '@', '#']    n = len(nuts)    nutboltmatch(nuts, bolts, n) # This code is contributed by Chitranayal
// Hashmap based solution to solveusing System;using System.Collections.Generic; public class GFG{   // function to match nuts and bolts  static void nutboltmatch(char[] nuts, char[] bolts, int n)  {    Dictionary<char,int> hash = new Dictionary<char,int>();     // creating a hashmap for nuts    for (int i = 0; i < n; i++)    {      hash.Add(nuts[i], i);    }     // searching for nuts for each bolt in hash map    for (int i = 0; i < n; i++)      if (hash.ContainsKey(bolts[i]))        nuts[i] = bolts[i];     // print the result    Console.WriteLine("matched nuts and bolts are-");    for (int i = 0; i < n; i++)      Console.Write(nuts[i] + " ");    Console.WriteLine();    for (int i = 0; i < n; i++)      Console.Write(bolts[i] + " ");  }   // Driver code  static public void Main ()  {     char[] nuts = { '@', '#', '$', '%', '^', '&' };    char[] bolts = { '$', '%', '&', '^', '@', '#' };    int n = nuts.Length;    nutboltmatch(nuts, bolts, n);   }} // This code is contributed by avanitrachhadiya2155
<script> // Hashmap based solution to solve // function to match nuts and boltsfunction nutboltmatch(nuts, bolts, n) {    let hash = new Map();     // creating a hashmap for nuts    for (let i = 0; i < n; i++)        hash.set(nuts[i], i);     // searching for nuts for each bolt in hash map    for (let i = 0; i < n; i++)        if (hash.has(bolts[i]))            nuts[i] = bolts[i];     // print the result    document.write("matched nuts and bolts are-<br>");    for (let i = 0; i < n; i++)        document.write(nuts[i] + " ");    document.write("<br>");    for (let i = 0; i < n; i++)        document.write(bolts[i] + " ");} // Driver code let nuts = ['@', '#', '$', '%', '^', '&'];let bolts = ['$', '%', '&', '^', '@', '#'];let n = nuts.length;nutboltmatch(nuts, bolts, n); </script>
Output:  
matched nuts and bolts are-
$ % & ^ @ # 
$ % & ^ @ # 
The time complexity for this solution is O(n).This article is contributed by Niteesh kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
ukasp
sanjeev2552
avanitrachhadiya2155
gfgking
Adobe
Amazon
Hike
MakeMyTrip
MAQ Software
Arrays
Hash
Amazon
Hike
MakeMyTrip
MAQ Software
Adobe
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Hashing | Set 3 (Open Addressing)
Count pairs with given sum