Skip to content

Commit 281e550

Browse files
committed
Add solution
1 parent 07f9012 commit 281e550

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// 1394. Find Lucky Integer in an Array
2+
// Given an array of integers arr, a lucky integer is an integer that has a frequency in the array equal to its value.
3+
// Return the largest lucky integer in the array. If there is no lucky integer return -1.
4+
5+
6+
// Solution: Counting
7+
8+
// Count the occurrances of each number and store it in a hashmap.
9+
// Go through each entry in the hashmap and record the maximum number which is equal to its frequency.
10+
11+
// Time Complexity: O(n) 1ms
12+
// Space Complexity: O(n) 56MB
13+
function findLucky(arr) {
14+
const count = {};
15+
for (let num of arr) {
16+
count[num] = (count[num] || 0) + 1;
17+
}
18+
let max = -1;
19+
for (let num in count) {
20+
if (num == count[num]) {
21+
max = Math.max(max, Number(num));
22+
}
23+
}
24+
return max;
25+
};
26+
27+
// Two test cases
28+
console.log(findLucky([2,2,3,4])) // 2
29+
console.log(findLucky([1,2,2,3,3,3])) // 3

0 commit comments

Comments
 (0)