JavaScript O(n) time and space using map


  • 1
    var lengthOfLongestSubstring = function(s) {
        if (s.length < 2) return s.length;
        let max = 1;
        const counts = { [s[0]]: 1 };
        let i = 0, j = 0;
        while (++j < s.length) {
            counts[s[j]] = (counts[s[j]] || 0) + 1;
            while (counts[s[j]] > 1) counts[s[i++]]--;
            max = Math.max(max, j - i + 1);
        }
        return max;
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.