Search by value in a Map in C++
Given a set of N pairs as a (key, value) pairs in a map and an integer K, the task is to find all the keys mapped to the given 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
#include "bits/stdc++.h"
using namespace std;
void printKey(map< int , int >& Map,
int K)
{
bool a = true ;
for ( auto & it : Map) {
if (it.second == K) {
cout << it.first << ' ' ;
a = false ;
}
}
if (a) {
cout << "-1" ;
}
}
int main()
{
map< int , int > Map;
Map[1] = 3;
Map[2] = 3;
Map[4] = -1;
Map[7] = 2;
Map[10] = 3;
int K = 3;
printKey(Map, K);
return 0;
}
|
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(N)
Last Updated :
24 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...