Longest Substring Without Repeating Characters in TypeScript

function lengthOfLongestSubstring(s: string): number {
    // Initialize a set to keep track of characters currently in the window
    let charSet = new Set();

    // Initialize the left pointer for the window, max length, and the current index
    let left = 0;
    let maxLength = 0;

    // Iterate through the string with the right pointer
    for (let right = 0; right < s.length; right++) {
        // If the character at the right pointer is in the set, it's a repeating character.
        // We remove characters from the set and move the left pointer until the character is removed.
        while (charSet.has(s[right])) {
            charSet.delete(s[left]);
            left++;
        }

        // Add the current character to the set and move the right pointer forward.
        charSet.add(s[right]);

        // Calculate the length of the current substring and update max length if necessary.
        maxLength = Math.max(maxLength, right - left + 1);
    }

    // Return the maximum length found.
    return maxLength;
}

PrevNext