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
leftcan jump past the earlier copy, and why the jump must bemax(left, last + 1)(stale indices, the "abba" case). - The window invariant: no repeats inside
s[left..right],leftnever decreases; window length isright - 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
dictas the last-seen map (or asetfor the shrinking variant),enumeratefor 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).