Find Lucky Integer in an Array - Problem

Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.

Return the largest lucky integer in the array. If there is no lucky integer return -1.

Input & Output

Example 1 — Basic Lucky Number
$ Input: arr = [2,2,3,4]
Output: 2
💡 Note: Number 2 appears 2 times, so 2 is lucky. Number 3 appears 1 time (3 ≠ 1), number 4 appears 1 time (4 ≠ 1). Only 2 is lucky.
Example 2 — No Lucky Numbers
$ Input: arr = [1,2,2,3,3,3]
Output: 3
💡 Note: Number 1 appears 1 time (1 = 1, lucky), number 2 appears 2 times (2 = 2, lucky), number 3 appears 3 times (3 = 3, lucky). The largest lucky number is 3.
Example 3 — Multiple Lucky Numbers
$ Input: arr = [7,7,7,7,7,7,7]
Output: 7
💡 Note: Number 7 appears 7 times, so 7 is lucky. This is the only number and it's lucky.

Constraints

  • 1 ≤ arr.length ≤ 500
  • 1 ≤ arr[i] ≤ 500

Visualization

Tap to expand
Find Lucky Integer in an Array INPUT arr = [2, 2, 3, 4] 2 idx 0 2 idx 1 3 idx 2 4 idx 3 Frequency Count: Value Freq 2 2 3 1 4 1 Green = Lucky (val == freq) ALGORITHM STEPS 1 Initialize Create frequency map Set result = -1 2 Count Frequencies Single pass through array map[num]++ 3 Check Lucky If freq[num] == num It's a lucky integer! 4 Track Maximum result = max(result, num) Update if larger lucky found Checking Values: 2: freq=2, 2==2 --> Lucky! max=2 3: freq=1, 3!=1 --> Not lucky 4: freq=1, 4!=1 --> Not lucky FINAL RESULT Largest Lucky Integer: 2 Why 2 is Lucky? Value 2 appears exactly 2 times in the array freq(2) = 2 = value Output: 2 Key Insight: A lucky integer has frequency equal to its value. Using a single-pass approach with early maximum tracking, we count frequencies and simultaneously check for lucky numbers, updating the maximum when found. Time Complexity: O(n) | Space Complexity: O(n) for the frequency map. TutorialsPoint - Find Lucky Integer in an Array | Single-Pass with Early Maximum
Asked in
Amazon 25 Google 20 Microsoft 15
28.5K Views
Medium Frequency
~15 min Avg. Time
845 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