A lucky integer is one whose value equals its frequency in the array. The simplest approach is to check each number by counting how many times it appears. If the count matches the number itself, it's a lucky integer. We track the largest one found.
res = -1 (no lucky integer found yet).num in the array:num appears by scanning the entire array.num, update res to the maximum of res and num.res.After sorting, identical numbers are grouped together. By traversing from right to left, we can count consecutive occurrences of each number. The first lucky integer we find (scanning from largest to smallest) is guaranteed to be the largest.
-1.We can count the frequency of each number in one pass using a hash map. Then we iterate through the map to find numbers where the key equals its value (frequency). This avoids repeated counting and is more efficient than brute force.
res = -1.res to the maximum of res and num.res.If we can modify the input array, we can use it as a frequency counter without extra space. For a number num, we use index num - 1 to store its frequency by making that position negative and decrementing it. After processing, a position i with value -x means the number i + 1 appeared x times.
i, follow the chain of values to increment counts:num.num is within bounds, decrement arr[num - 1] (making it negative if needed) to track frequency.i, check if -arr[i] == i + 1 (frequency equals the number).-1 if none exists.class Solution:
def findLucky(self, arr: List[int]) -> int:
n = len(arr)
for i in range(n):
prev, num = i, arr[i]
while 0 < num <= n:
nxt = arr[num - 1]
arr[num - 1] = min(0, arr[num - 1]) - 1
if num - 1 <= i or num - 1 == prev:
break
prev = num - 1
num = nxt
for i in range(n - 1, -1, -1):
if -arr[i] == i + 1:
return i + 1
return -1We can use bit manipulation to store both the original value and the frequency count in the same array element. Since values are at most 500, they fit in 10 bits. We use the lower 10 bits for the original value and the upper bits for the count. This allows in-place frequency tracking.
1 << 10.i, extract the count by right-shifting by 10 bits.i + 1, return i + 1 (this is the largest lucky integer).-1.A lucky integer only exists if a number's value equals its frequency. If no such number is found, the function must return -1. Forgetting to initialize the result to -1 or failing to handle the case where no lucky integer exists will produce incorrect output for inputs like [1, 1] where no number satisfies the condition.
When multiple lucky integers exist in the array, you must return the largest one. Simply returning the first lucky integer found without comparing it to previously found ones produces wrong results. Always use max(result, num) when a lucky integer is found, or iterate from largest to smallest and return immediately upon finding one.