Skip to the solution
MediumDSA9 min read

How do you find the longest substring without repeating characters?

526 views

The problem

Question presented to candidate: "Given a string, find the length of the longest substring that has no repeating characters. For example, for 'abcabcbb' the answer is 3, for 'abc'. Please write it in Python and walk me through its complexity."

What a strong answer should cover:

  • Brute force over all substrings is O(nยฒ) to O(nยณ); the expected answer is a variable-size sliding window in O(n).
  • A last-seen index map so left can jump past the earlier copy, and why the jump must be max(left, last + 1) (stale indices, the "abba" case).
  • The window invariant: no repeats inside s[left..right], left never decreases; window length is right - left + 1.
  • Space O(min(n, k)) for alphabet size k, and the set-based alternative that shrinks one step at a time.
  • Python specifics: a dict as the last-seen map (or a set for the shrinking variant), enumerate for index and character together, and the fact that Python strings index by Unicode code point, so an emoji counts as one character.

Clarifying questions expected:

  • "What is the character set โ€” ASCII, lowercase only, or Unicode?"
  • "Do you want the length or the substring itself?"

Code / implementation expected: Yes โ€” a longest_unique(s) function in Python returning the length (and optionally the substring).

  • strings
  • sliding-window

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

9 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonSliding window with last-seen indices on eight inputs
PythonWhy max(left, last + 1): trace and buggy vs fixed vs set

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 84 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

What is the difference between BFS and DFS?

Continue