</>

1394. Find Lucky Integer in an Array

Easy
Arrays & Hashing Time O(n) Space O(MAX_VAL)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Arrays & Hashing
Time
O(n)
Space
O(MAX_VAL)

Standard Solution (C++)

SummaryGiven an array of integers, find the largest value that appears exactly as many times as its own numeric value (called a "lucky" integer), or return -1 if none exists.

Approach
  • Build a frequency map counting how many times each number appears in the array.
  • Iterate over all entries in the map, tracking the maximum value whose count equals its value.
  • A single pass over the map suffices because we compare each entry and keep a running maximum.
  • Since array values are bounded by 500 (per constraints), the map holds at most 500 distinct keys, keeping both passes O(n).
#include <vector>
#include <unordered_map>
using namespace std;

class Solution {
public:
    int findLucky(vector<int>& arr) {
        unordered_map<int, int> freq;
        for (int x : arr)
            ++freq[x];

        int result = -1;
        for (auto& [val, cnt] : freq)
            if (val == cnt)
                result = max(result, val);  // keep the largest lucky integer

        return result;
    }
};
Time O(n) Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <vector>
using namespace std;

class Solution {
   public:
    int findLucky(vector<int>& arr) {
        int count[501] = {0};  // index 0 is unused
        for (int n : arr)
            ++count[n];
        for (auto n = arr.size(); n > 0; --n)
            if (n == count[n])
                return n;
        return -1;
    }
};

// Time Complexity: O(n). Since MAX_VAL is constant.
// Space Complexity: O(MAX_VAL).
Time O(n) Space O(MAX_VAL)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern