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).
1function findLucky(arr) {
2 const freq = {};
3 for (let num of arr) {
4 freq[num] = (freq[num] || 0) + 1;
5 }
6 let maxLucky = -1;
7 for (let num in freq) {
8 if (Number(num) === freq[num] && Number(num) > maxLucky) {
9 maxLucky = Number(num);
10 }
11 }
12 return maxLucky;
13}
14
15const arr = [1, 2, 2, 3, 3, 3];
16console.log(findLucky(arr));
Using object properties, this JavaScript solution counts frequencies of each number in an array. It then checks for the largest number that equals its frequency, iterating over the object's properties.
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.