longest-substring
· Explorer
- src
- db
1// Longest Substring Without Repeating Characters2// Time: O(n) Space: O(min(m,n))34export function lengthOfLongestSubstring(s: string): number {5 const seen = new Map<string, number>();6 let left = 0, best = 0;78 for (let right = 0; right < s.length; right++) {9 const c = s[right];10 if (seen.has(c) && seen.get(c)! >= left) {11 left = seen.get(c)! + 1;12 }13 seen.set(c, right);14 best = Math.max(best, right - left + 1);15 }16 return best;17}
Hint · line 8
Make sure left only moves forward — otherwise duplicates outside the window will reset it incorrectly.
OutputProblemsTests 4 / 4 passed
$ tsx tests.ts
✓ "abcabcbb" → 3
✓ "bbbbb" → 1
✓ "pwwkew" → 3
✓ "" → 0
Runtime: 14ms · Memory: 4.2MB · Beats 87%
AI Copilot
Hint mode
Copilot
I see you're using a Map — nice. Want a hint about the edge case for empty strings, or to discuss complexity?
You
Why does left = seen.get(c)! + 1 need the bound check?
Copilot
Without seen.get(c)! >= left, a duplicate seen before the window started would pull left backwards — re-introducing characters you already passed. Try "abba" in your head.
Quick actions
mainTypeScriptUTF-8LF 0 errors · 1 warning AI ready