Longest Substring Without Repeating Characters LeetCode solution in JavaScript

1
var lengthOfLongestSubstring = function (s) {
2
// keeps track of the most recent index of each letter.
3
const seen = new Map();
4
// keeps track of the starting index of the current substring.
5
let start = 0;
6
// keeps track of the maximum substring length.
7
let maxLen = 0;
8

9
for (let i = 0; i < s.length; i++) {
10
// if the current char was seen, move the start to (1 + the last index of this char)
11
// max prevents moving backward, 'start' can only move forward
12
if (seen.has(s[i])) start = Math.max(seen.get(s[i]) + 1, start);
13
seen.set(s[i], i);
14
// maximum of the current substring length and maxLen
15
maxLen = Math.max(i - start + 1, maxLen);
16
}
17

18
return maxLen;
19
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0