Hey array detectives! 🔍
Today we’re tackling a charming problem that blends frequency counting and a bit of luck. The idea? Identify integers in an array whose value matches their count. These are called lucky integers — and our goal is to find the largest one!
Let's dive into the logic and crack the problem in all three major languages. 🎯
🧠 Problem Summary
You're given:
- An array
arr
of integers.
Your goal:
Return the largest lucky integer in the array. An integer is considered lucky if its frequency in the array equals its own value.
If no such integer exists, return -1
.
💡 Intuition
We simply need to:
- Count the frequency of each number in the array.
- Check which numbers have frequency equal to their value.
- Return the largest such number.
Since values are capped at 500, we can use a frequency array for efficient counting.
🛠️ C++ Code
class Solution {
public:
int findLucky(vector<int>& arr) {
vector<int> count(arr.size() + 1);
for (const int a : arr)
if (a <= arr.size())
++count[a];
for (int i = arr.size(); i >= 1; --i)
if (count[i] == i)
return i;
return -1;
}
};
🐍 Python Code
class Solution:
def findLucky(self, arr: List[int]) -> int:
from collections import Counter
count = Counter(arr)
res = -1
for num, freq in count.items():
if num == freq:
res = max(res, num)
return res
💻 JavaScript Code
var findLucky = function(arr) {
const freq = new Map();
for (const num of arr) {
freq.set(num, (freq.get(num) || 0) + 1);
}
let res = -1;
for (const [num, count] of freq.entries()) {
if (num === count) {
res = Math.max(res, num);
}
}
return res;
};
📝 Key Takeaways
- Use frequency maps or arrays to track counts.
- Look for numbers where
value == frequency
. - Always return the largest such number (or
-1
if none).
✅ Final Thoughts
This problem is a great exercise in hash maps and frequency counting. Simple, clean, and a great fit for coding interviews or warmups.
Keep the code flowing, and see you in the next breakdown! 🚀
Top comments (4)
Well Explained
Thanks Anna
Thank you for the info
Your most welcome Emily!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.