I first count how many times each number appears in the array. I use a frequency map (like Python's Counter
) to make this easier. Then, I go through each number and check if its frequency is equal to the number itself. If it is, I consider it a "lucky" number. While doing this, I keep track of the largest such lucky number I find. If I don't find any number that satisfies the condition, I return -1
; otherwise, I return the largest lucky number found.
class Solution:
def findLucky(self, arr: List[int]) -> int:
freq = Counter(arr)
result = -1
for num, count in freq.items():
if num == count:
result = max(result, num)
return result
- Time: O(n)
- Space: O(n)
