Search by value in a Map in C++

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include "bits/stdc++.h"
using namespace std;
  
// Function to find the key values
// according to given mapped value K
void printKey(map<int, int>& 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 Code
int main()
{
    map<int, int> Map;
  
    // Given map
    Map[1] = 3;
    Map[2] = 3;
    Map[4] = -1;
    Map[7] = 2;
    Map[10] = 3;
  
    // Given value K
    int K = 3;
  
    // Function call
    printKey(Map, K);
    return 0;
}

chevron_right


Output:

1 2 10

Time Complexity: O(log N), where N is the number of pairs stored in map.
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.