Search by value in a Map in C++

• Difficulty Level : Easy
• Last Updated : 03 Mar, 2021

Given set of N pairs as a (key, value) pairs in a map and an integers K, task is to find all the keys mapped to the give value K. If there is no key value mapped to K then print “-1”.
Examples:

Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 3
Output: 1 2 10
Explanation:
The 3 key value that is mapped to value 3 are 1, 2, 10.
Input: Map[] = { {1, 3}, {2, 3}, {4, -1}, {7, 2}, {10, 3} }, K = 10
Output: -1
Explanation:
There is no any key value that is mapped to value 10.

Approach: The idea is to traverse the given map and print all the key value which are mapped to the given value K. Below is the loop used to find all the key value:

for(auto &it : Map) {
if(it.second == K) {
print(it.first)

If there is no value mapped with K then print “-1”.
Below is the implementation of the above approach:

CPP

 // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to find the key values// according to given mapped value Kvoid printKey(map& Map,              int K){     // If a is true, then we have    // not key-value mapped to K    bool a = true;     // Traverse the map    for (auto& it : Map) {         // If mapped value is K,        // then print the key value        if (it.second == K) {            cout << it.first << ' ';            a = false;        }    }     // If there is not key mapped with K,    // then print -1    if (a) {        cout << "-1";    }} // Driver Codeint main(){    map Map;     // Given map    Map = 3;    Map = 3;    Map = -1;    Map = 2;    Map = 3;     // Given value K    int K = 3;     // Function call    printKey(Map, K);    return 0;}
Output:
1 2 10

Time Complexity: O(N), where N is the number of pairs stored in map. This is because we are traversing all the pairs once.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up