Find Longest Awesome Substring LeetCode solution in JavaScript

1
var longestAwesome = function (s) {
2
// freq starts with 0:0 because 9 0s is also a state and if I come across a
3
// 0 down the road, that means that the whole array up to index i is of the required type
4
let firstIndex = { 0: 0 },
5
result = -1,
6
curr = 0;
7
for (let i = 0; i < s.length; i++) {
8
curr ^= 1 << s[i];
9
// Check if you have seen curr^0=curr before,
10
// because that would make the inbetween elements' xor = 000000000
11
if (firstIndex[curr] !== undefined)
12
result = Math.max(result, i - firstIndex[curr] + 1);
13
// Check all the other xors, because that would make
14
// the inbetween elements of the required type (100000000,010000000,......,000000001)
15
for (let j = 0; j < 10; j++) {
16
let ele = 1 << j;
17
if (firstIndex[curr ^ ele] !== undefined)
18
//i-firstIndex[curr^ele] because on freq I saved
19
//the smallest index where I last met curr^ele
20
result = Math.max(result, i - firstIndex[curr ^ ele] + 1);
21
}
22
if (firstIndex[curr] === undefined) firstIndex[curr] = i + 1; // +1 cos 0th place is for my 0 state
23
}
24

25
return result;
26
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0