DEV Community

Cover image for 🏯Beginner-Friendly Guide "Find Lucky Integer in an Array" – LeetCode 1394 (C++ | Python | JavaScript)
Om Shree
Om Shree

Posted on

🏯Beginner-Friendly Guide "Find Lucky Integer in an Array" – LeetCode 1394 (C++ | Python | JavaScript)

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:

  1. Count the frequency of each number in the array.
  2. Check which numbers have frequency equal to their value.
  3. 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;
  }
};
Enter fullscreen mode Exit fullscreen mode

🐍 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
Enter fullscreen mode Exit fullscreen mode

💻 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;
};
Enter fullscreen mode Exit fullscreen mode

📝 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)

Collapse
 
thedeepseeker profile image
Anna kowoski

Well Explained

Collapse
 
om_shree_0709 profile image
Om Shree

Thanks Anna

Collapse
 
emboe profile image
Emily

Thank you for the info

Collapse
 
om_shree_0709 profile image
Om Shree

Your most welcome Emily!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.