Find Lucky Integer in an Array - Problem
Find Lucky Integer in an Array
Given an array of integers
For example, if the number
Goal: Return the largest lucky integer in the array. If there is no lucky integer, return
Example: In array
This is a classic frequency counting problem that tests your ability to efficiently track and compare element occurrences.
Given an array of integers
arr, a lucky integer is an integer that has a frequency in the array equal to its value.For example, if the number
3 appears exactly 3 times in the array, then 3 is a lucky integer.Goal: Return the largest lucky integer in the array. If there is no lucky integer, return
-1.Example: In array
[2, 2, 3, 4], the number 2 appears 2 times, so it's lucky! The number 3 appears 1 time (not 3 times), so it's not lucky.This is a classic frequency counting problem that tests your ability to efficiently track and compare element occurrences.
Input & Output
example_1.py โ Basic Case
$
Input:
arr = [2, 2, 3, 4]
โบ
Output:
2
๐ก Note:
The number 2 appears exactly 2 times in the array, making it a lucky integer. Numbers 3 and 4 each appear only 1 time, so they are not lucky. Therefore, 2 is the largest (and only) lucky integer.
example_2.py โ Multiple Lucky Integers
$
Input:
arr = [1, 2, 2, 3, 3, 3]
โบ
Output:
3
๐ก Note:
Number 1 appears 1 time (lucky), number 2 appears 2 times (lucky), and number 3 appears 3 times (lucky). Among all lucky integers [1, 2, 3], the largest is 3.
example_3.py โ No Lucky Integers
$
Input:
arr = [2, 2, 2, 3, 3]
โบ
Output:
-1
๐ก Note:
Number 2 appears 3 times (not equal to 2), and number 3 appears 2 times (not equal to 3). Since no number's frequency equals its value, return -1.
Constraints
- 1 โค arr.length โค 500
- 1 โค arr[i] โค 500
- All array elements are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Count Guests
Create a registry counting how many people have each invitation number
2
Find Lucky Groups
Check which invitation numbers match their group sizes exactly
3
Pick Highest
Among all lucky groups, select the one with the highest invitation number
Key Takeaway
๐ฏ Key Insight: Hash tables are perfect for frequency counting problems. The two-pass approach (count then search) is clean and efficient, turning an O(nยฒ) brute force into an elegant O(n) solution!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code