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
Similar to our first C solution but highlighting direct array access instead of hash maps, this implementation calculates frequency using a fixed-size array from 1 to 500. The result is determined by comparing each index with its frequency count directly.