Given an array of integers arr
, a lucky integer is an integer that has a frequency in the array equal to its value.
Return the largest lucky integer in the array. If there is no lucky integer return -1
.
An integer where frequency = value
Value: 3, Frequency: 3 → Lucky! ✨
Create a frequency map to count occurrences of each number
Check each number where frequency equals the value
Return the largest lucky number, or -1 if none exist
Single pass to count frequencies + single pass to find lucky numbers
HashMap to store frequency counts
function findLucky(arr) {
// Count frequencies
const freq = new Map();
for (const num of arr) {
freq.set(num, (freq.get(num) || 0) + 1);
}
// Find lucky numbers
let maxLucky = -1;
for (const [num, count] of freq) {
if (num === count) {
maxLucky = Math.max(maxLucky, num);
}
}
return maxLucky;
}
Input: [2,2,3,4]
Output: 2
Explanation: Only 2 appears 2 times
Input: [1,2,2,3,3,3]
Output: 3
Explanation: 1, 2, and 3 are lucky. Return max: 3
Input: [2,2,2,3,3]
Output: -1
Explanation: No lucky numbers exist
Count the frequency of each number in the array using a HashMap or frequency array.
A number is lucky if its frequency equals its value. Check this condition for each unique number.