Find Lucky Integer in an Array (LeetCode 1394): Solution and Explanation

Easy
Array
Hash Table
Counting

A value is lucky when it appears exactly as many times as its own value. Return the largest lucky value, or -1 if there is none.

Intuition

Whether a value is lucky depends only on how many times it appears, so the first job is counting.

Values are between 1 and 500, so a plain array of 501 counters is enough; no hash map is needed.

We want the largest lucky value. Checking candidates from 500 downward means the first match is the answer and the scan can stop there.

Approach: Count, then scan from the top

  1. Create freq of size 501 filled with zeros.
  2. For each x in arr, add one to freq[x].
  3. For v from 500 down to 1, return v as soon as freq[v] == v.
  4. If the loop ends, return -1.

Step-by-step example

arr = [1,2,2,3,3,3]
  1. Counting gives freq[1] = 1, freq[2] = 2, freq[3] = 3.
  2. Scan from 500 down. Every value above 3 has count 0, which never equals a positive value.
  3. At v = 3, freq[3] = 3 equals 3, so return 3. The smaller lucky values 2 and 1 are never examined.

Code: Python, Java, C++

1class Solution:
2    def findLucky(self, arr: List[int]) -> int:
3        freq = [0] * 501
4        for x in arr:
5            freq[x] += 1
6        for v in range(500, 0, -1):
7            if freq[v] == v:
8                return v
9        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Count, then scan from the top O(n)
Hash map of counts O(n)
Sort and count runs O(n log n)
Time

O(n)

One pass to count n values plus a fixed scan of 500 slots.

Space

O(1)

The counting array has 501 slots no matter how long arr is.

Other approaches

Hash map of counts (time O(n), space O(n))

Count with a dictionary, then take the maximum key whose count equals the key. Works without a known value range.

Sort and count runs (time O(n log n), space O(1))

Sort the array, walk runs of equal values from the end, and return the first run whose length equals its value.

Common mistakes

  • Returning the first lucky value found in a left-to-right scan of arr instead of the largest.
  • Starting the downward scan at 0: freq[0] is always 0, so 0 would look lucky. Stop at 1.
  • Sizing the counter array as 500, which makes index 500 out of bounds.

Frequently asked questions

Why scan from 500 down instead of tracking a maximum?

Both work. Scanning down lets you return on the first match, and it keeps the code to one comparison per value.

Can a value appear more times than itself and still be lucky?

No. The count has to equal the value exactly; four copies of 3 make 3 not lucky.

What if every value is distinct?

Each count is 1, so only the value 1 can be lucky. If 1 is present the answer is 1, otherwise -1.