Solution
The question is pretty straightforward. Iterate through an array and keep track of the frequencies using a hashmap. Then iterate through the hashmap, check which number’s frequency is equal to the number itself and return the maximum such number.
int findLucky(vector<int>& arr) {
unordered_map<int, int> freq;
for (int i : arr)
freq[i]++;
int res = -1;
for (auto p : freq) {
if (p.first == p.second)
res = max(res, p.first);
}
return res;
}
Time complexity: O(n) Space complexity: O(n)