Walkthrough of the problem "Find Lucky Integer in an Array"
2 min
Article
DSA
LeetCode
HashMap
Array
C++
Algorithm
Table of Contents
Intro
The problem does seem simple, as its clear that we have to find the number of time a number is repeating and if count(x)==x then we print the largest number of the array.
The problem is very simple when its done using hashmap, try two pointers if it works then its cool. I used hashmap in cpp (unordered_map).
In cpp, STL libraries have unordered_map. Just add it with #include <unordered_map>. Refer more about unordered_map .
First approach
I started to go with two pointers as its very obvious to count and add it to an empty array. But i realized using two pointers for a large array is not good for the time complexity.
So using hashmap, its pretty obvious we have to do the normal procedure we do with hashmap.
Read the array, build hasmap
Then loop through the hashmap to get the output
After including necessary libraries, we go wit this
// declare a unordered map with int, int key value pair
unordered_map<int,int> map;
// loop thru the array to store in hashmap
for(int num : array){
map[num]++
}
What we did now is building the hashmap from the given array
Code
classSolution{public:intfindLucky(vector<int>& arr){// unordered map declaration unordered_map<int,int> freq;int maxLuck =-1;// to get the max numberfor(int num : arr){ freq[num]++;}for(auto it : freq){if(it.first == it.second) maxLuck =max(maxLuck,it.first);}return maxLuck;}};
Time and Space Complexity
Time Complexity: O(n), where n = number of elements in the array
Space Complexity: O(n), due to the hashmap storing frequency
Conclusion
The Lucky Number problem is a great intro to hashmap-based frequency counting.
The logic is clean, the code is simple, and the idea is powerful — count, compare, and track max.