Sponsored
Sponsored
This approach involves using a hash map (or dictionary) to store the frequency of each integer in the array. Once frequencies are calculated, iterate through the map to find integers whose value is equal to their frequency, and track the maximum of such values.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), since the frequency array is of constant size (501).
1def findLucky(arr):
2 freq = {}
3 for num in arr:
4 freq[num] = freq.get(num, 0) + 1
5 maxLucky = -1
6 for num, count in freq.items():
7 if num == count and num > maxLucky:
8 maxLucky = num
9 return maxLucky
10
11arr = [1, 2, 2, 3, 3, 3]
12print(findLucky(arr))
In this Python solution, a dictionary is used to store the frequency of each integer. We then iterate through this dictionary to find the largest lucky number.
This approach involves using an array to directly track the frequency of each integer. By using an array of fixed size, we can avoid using a hash map or dictionary, which optimizes space usage when the domain of the input elements is known.
Time Complexity: O(n), where n is the length of the array.
Space Complexity: O(1), using a constant-size array.
1
Using a pre-initialized array in Python, this solution computes frequencies without dictionaries. It ensures efficiency by exploiting the fixed range of input values.