LeetCode #3 – Longest Substring Without Repeating Characters


Problem Statement

  1. Task



Sliding Window with a Set (O(n))

  1. High-Level Idea


  2. Core Logic (TypeScript)

  3. function lengthOfLongestSubstring(s: string): number {
        const memo = new Set<string>();  // current window's characters
    
        let ans = 0;
        let l = 0;                        // left pointer
    
        for (let r = 0; r < s.length; r++) {
            const c = s[r];
    
            // If c is already in the window, shrink from the left
            if (memo.has(c)) {
                while (s[l] !== c) {
                    memo.delete(s[l]);
                    l++;
                }
                memo.delete(s[l]);  // remove the previous occurrence of c
                l++;
            }
    
            memo.add(c);                   // extend window with s[r]
    
            // Update the best length so far
            if (r - l + 1 > ans) {
                ans = r - l + 1;
            }
        }
    
        return ans;
    };
    
    const solution1 = lengthOfLongestSubstring;
    
    export {};
    


Example Walkthrough

Take s = "pwwkew".

Step (r index) Character l (left) Window s[l..r] Set contents ans Operation
r = 0 'p' 0 "p" { p } 1 Add 'p', update ans = 1
r = 1 'w' 0 "pw" { p, w } 2 Add 'w', update ans = 2
r = 2 'w' 1 "ww""w" { w } 2 Duplicate 'w': move l forward, remove 'p', then old 'w'
r = 3 'k' 2 "wk" { w, k } 2 Add 'k', ans stays 2
r = 4 'e' 2 "wke" { w, k, e } 3 Add 'e', update ans = 3
r = 5 'w' 3 "kew" { k, e, w } 3 Duplicate 'w': shrink until previous 'w' removed, final window "kew"



Why This Is O(n)