Find Lucky Integer in an Array (LeetCode 1394): Solution and Explanation
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
- Create freq of size 501 filled with zeros.
- For each x in arr, add one to freq[x].
- For v from 500 down to 1, return v as soon as freq[v] == v.
- If the loop ends, return -1.
Step-by-step example
arr = [1,2,2,3,3,3]
- Counting gives freq[1] = 1, freq[2] = 2, freq[3] = 3.
- Scan from 500 down. Every value above 3 has count 0, which never equals a positive value.
- 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 -11class Solution {
2 public int findLucky(int[] arr) {
3 int[] freq = new int[501];
4 for (int x : arr) {
5 freq[x]++;
6 }
7 for (int v = 500; v >= 1; v--) {
8 if (freq[v] == v) {
9 return v;
10 }
11 }
12 return -1;
13 }
14}1class Solution {
2public:
3 int findLucky(vector<int>& arr) {
4 vector<int> freq(501, 0);
5 for (int x : arr) {
6 freq[x]++;
7 }
8 for (int v = 500; v >= 1; v--) {
9 if (freq[v] == v) {
10 return v;
11 }
12 }
13 return -1;
14 }
15};Time and space complexity
O(n)
One pass to count n values plus a fixed scan of 500 slots.
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.