Given an array of integers arr, a lucky integer is an integer which 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.
Example:
Input: arr = [2,2,3,4]
Output: 2
Explanation: The frequency of 2 is 2.
Input: arr = [1,2,2,3,3,3]
Output: 3
Explanation: The frequency of 3 is 3.
Input: arr = [2,2,2,3,3]
Output: -1
Explanation: There are no lucky numbers in the array.
Input: arr = [5]
Output: -1
Explanation: There are no lucky numbers in the array.
Input: arr = [7,7,7,7,7,7,7]
Output: 7
-1 as there won’t be any integers to evaluate.collections.Counter to count the frequencies of each number in the array.-1.from collections import Counter
def findLucky(arr):
freq = Counter(arr)
lucky_integers = [num for num, count in freq.items() if num == count]
return max(lucky_integers, default=-1)
# Example Usages
print(findLucky([2, 2, 3, 4])) # Output: 2
print(findLucky([1, 2, 2, 3, 3, 3])) # Output: 3
print(findLucky([2, 2, 2, 3, 3])) # Output: -1
print(findLucky([5])) # Output: -1
print(findLucky([7, 7, 7, 7, 7, 7, 7])) # Output: 7
Counter takes O(n) time, where n is the number of elements in the array.O(k) time where k is the number of unique elements which in the worst case is O(n).O(m) where m is the number of lucky integers. In the worst case, m is also O(n).Thus, the overall time complexity is:
n is the number of elements in the array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?