PPractick

DSA interview question

Longest Substring Without Repeating Characters

Medium · Algorithms · Topics: sliding window, hash set, string

The problem

A password-strength meter rewards long stretches of distinct characters. For a given string, it needs the length of the longest contiguous substring with no repeated character. Checking every substring is O(n²) or worse. A sliding window does it in one pass: extend the right end one character at a time, and when that character already appears inside the window, jump the left end to just past its previous occurrence. Remembering the last index of each character makes the jump O(1).

Example: "abcabcbb" → 3 ("abc").

Function signature

int lengthOfLongestSubstring(const string& s);

Test cases

InputOutputExplanation
"abcabcbb"3"abc"
"bbbbb"1
"pwwkew"3"wke"; "pwke" is not contiguous
""0
"abba"2The left end must never move backwards
"dvdf"3"vdf"

(Confirm: substring means contiguous; characters are arbitrary bytes, including spaces and symbols.)

How interviewers phrase it

Clarifying questions to ask

  1. Substring (contiguous) or subsequence? (Substring.)
  2. What character set? (ASCII: a 256-entry table works; for Unicode, use a hash map.)
  3. Length only, or the substring itself? (Length; tracking the start is a small extension.)

Follow-ups to expect

  1. "Why check last[c] >= left?"
  2. "Set-based variant?"
  3. "Why is it O(n)?"
  4. "How do you return the substring?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in