Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Sliding window

Longest run of distinct characters

Medium · Target 15 minutes · Sliding window· Type asked at

Given a string s, return the length of the longest contiguous substring in which no character repeats.

Examples

InputOutputWhy
s = "abcabcbb"3"abc".
s = "bbbbb"1"b".
s = "pwwkew"3"wke". "pwke" is a subsequence, not a substring.

Constraints

  • 0 ≤ |s| ≤ 10⁵
  • s contains printable ASCII characters

Hints

Hint 1

Brute force checks every substring in O(n²) or worse. What work is being repeated?

Hint 2

Keep a window that is always valid — no repeats inside it — and never move the left edge backwards.

Hint 3

When you meet a character you have seen inside the current window, jump the left edge to just past its previous position. Store the last index of each character.

Where people lose marks

  • Moving the left edge back when an old duplicate appears outside the window. Take max(lo, prev + 1).
  • Forgetting the empty string, which must return 0.
  • Clearing the whole map on a violation. That turns the scan quadratic; only the left edge needs to move.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.