Lock & Key problem using Hash-map

A list of different locks and another list of keys are given. Our task is to find the correct match of lock and key from the given list, and assign that key with the lock when it is correct.

In this approach we will traverse all of the locks and create a hash-map, after that, each key is searched in the hash-map. When the key is matches, then that is marked as a valid key and assigned with a lock.

Input and Output

Input:
The lists of locks and keys.
lock = { ),@,*,^,(,%, !,$,&,#} key = { !, (, #, %, ), ^, &, *,$, @ }
Output:
After matching Locks and Keys:
Locks: ! ( # % ) ^ & * $@ Keys: ! ( # % ) ^ & *$ @

Algorithm

lockAndKeyProblem(lock, key, n)

Input: The list of locks, the list of keys, n.

Output: Find which key is for which lock.

Begin
define hashmap
for i in range (0 to n-1), do
hashmap[lock[i]] := i  //set hashmap for locks
done

for i in range (0 to n-1), do
if key[i] is found in the hashmap, then
lock[i] = key[i]
done
End

Example

#include<iostream>
#include<map>
using namespace std;

void show(char array[], int n) {
for(int i = 0; i<n; i++)
cout << array[i] << " ";
}

void lockAndKeyProblem(char lock[], char key[], int n) {
map<char, int> hashMap;
for(int i = 0; i<n; i++)
hashMap[lock[i]] = i;           //hash map for locks

for(int i = 0; i<n; i++) //for each keys for each lock
if(hashMap.find(key[i]) != hashMap.end()) {
lock[i] = key[i];
}
}

int main() {
char lock[] = {')','@','*','^','(','%','!','$','&','#'}; char key[] = {'!','(','#','%',')','^','&','*','$','@'};
int n = 10;
lockAndKeyProblem(lock, key, n);
cout << "After matching Locks and Keys:"<<endl;
cout << "Locks: "; show(lock, n); cout << endl;
cout << "Keys: "; show(key, n); cout << endl;
}

Output

After matching Locks and Keys:
Locks: ! ( # % ) ^ & * $@ Keys: ! ( # % ) ^ & *$ @

Updated on: 17-Jun-2020

566 Views