Longest Distinct Substring
Return the greatest length of a contiguous lowercase-letter sequence with no repeated letter.
Return the greatest length of a contiguous lowercase-letter sequence with no repeated letter.
Input and constraints
- Use lowercase letters encoded as 0 (a) through 25 (z).
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): last = [0] * (26) left = 0 right = 0 best = 0 while (right < len(values)): key = values[right] left = max(left, last[key]) best = max(best, ((right - left) + 1)) last[key] = (right + 1) right = (right + 1) return bestVisualizer
Step 1 of 7Inspect the current state
Exclude the previous occurrence when it lies inside this window.
Variable watch
Step explanation
Exclude the previous occurrence when it lies inside this window.
Worked explanation
Seat guests in a continuous row while admitting each badge colour only once.
Guided solution
Use each letter’s previous position to move the left boundary just beyond a conflicting occurrence.
O(n + 26) time · O(26) auxiliary space
Examples
Worked example · {"values":[0,1,2,0,1,3],"target":0} ⇒ 4
Edge case 1 · {"values":[],"target":0} ⇒ 0
Edge case 2 · {"values":[0,0],"target":0} ⇒ 1
Progressive hints
Hint 1
Seat guests in a continuous row while admitting each badge colour only once.Hint 2
Use each letter’s previous position to move the left boundary just beyond a conflicting occurrence.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
The left boundary must never move backwards to a stale occurrence.
Interview follow-up
What changes for arbitrary Unicode input?