Find Lucky Integer in an Array - Problem
Find Lucky Integer in an Array

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
๐ŸŽฏ Lucky Integer Detection ProcessInput: [2, 2, 3, 4]2234Frequency Count:2 โ†’ 23 โ†’ 14 โ†’ 1Lucky Check:2 == 2 โœ“ LUCKY!3 != 1 โœ— Not Lucky4 != 1 โœ— Not Lucky๐Ÿ€ Result: 2Largest Lucky Integer Found!Algorithm Complexity:โฑ๏ธ Time: O(n) - Single pass through array + hash map๐Ÿ’พ Space: O(k) - Hash map stores unique elements๐Ÿš€ Much better than O(nยฒ) brute force!Key Steps:1. Count frequency of each element2. Check if frequency equals element value3. Track maximum lucky integer
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!
Asked in
Amazon 25 Google 18 Meta 12 Microsoft 8
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen