How to Fix Longest Substring Without Repeating Errors
In this tutorial, you'll learn about How to Fix Longest Substring Without Repeating Errors. We cover key concepts, practical examples, and best practices.
Fix longest substring without repeating errors when character position reset wrong or left pointer doesn't jump to after duplicate.
Quick Fix
Wrong
def lnrc(s):
l=mx=0; seen=set()
for r in range(len(s)):
while s[r] in seen:
seen.remove(s[l]); l+=1
seen.add(s[r]); mx=max(mx,r-l+1)
return mx
While loop removes characters one by one. O(n) amortized but can be O(n^2) worst case.
Right
def lnrc(s):
last={}; l=0; mx=0
for r,c in enumerate(s):
if c in last and last[c]>=l:
l=last[c]+1 # jump left past duplicate
last[c]=r; mx=max(mx,r-l+1)
return mx
'abcabcbb' -> 3 ('abc'). 'bbbbb' -> 1 ('b'). 'pwwkew' -> 3 ('wke'). O(n).
Prevention
Track last seen index of each character. Jump left pointer to last occurrence+1 on duplicate.
DodaTech Tools
Doda Browser's algorithm visualizer steps through DSA operations line by line. DodaZIP archives implementation patterns for team sharing. Durga Antivirus Pro detects memory corruption patterns in algorithm implementations.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro