Maximum Equal Frequency LeetCode solution in JavaScript

1
// *NOTE: ternary operator is to handle if key is undefined since javascript doesn't have a default object value
2

3
var maxEqualFreq = function (nums) {
4
// create cache to count the frequency of each number
5
const numCnt = {};
6

7
// create cache to count the number of 'number of frequencies'
8
// e.g. [1,2,3,2,4,4,3,1,5]
9
// { 1: 1 1 number appeared with a frequency of 1
10
// 2: 3 } 3 numbers appeared with a frequency of 2
11
const cntFreq = {};
12

13
// holds the maximum frequency a number has appeared
14
let maxFreq = 0;
15

16
// holds solution
17
let result = 0;
18

19
// iterate through numbers
20
for (let i = 0; i < nums.length; i++) {
21
// get current number;
22
const num = nums[i];
23

24
// subtract one from the current frequency of the current number
25
cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] - 1 : -1;
26

27
// increase the count of the current number
28
numCnt[num] = numCnt[num] ? numCnt[num] + 1 : 1;
29

30
// add one to the current frequency of the current number
31
cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] + 1 : 1;
32

33
// if the current frequency is more than the max frequency update the max frequency
34
if (maxFreq < numCnt[num]) maxFreq = numCnt[num];
35

36
// if max frequency is 1 or
37
// if the max frequency multiplied by the number of values with that frequency equals the current index or
38
// if the result of the 1 less than the max frequency equals to the current index
39
// update result
40
if (
41
maxFreq === 1 ||
42
maxFreq * cntFreq[maxFreq] === i ||
43
(maxFreq - 1) * (cntFreq[maxFreq - 1] + 1) === i
44
) {
45
result = i + 1;
46
}
47
}
48
return result;
49
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0