interviewmind

Longest Substring Without Repeating Characters

Longest Substring Without Repeating Characters is a medium coding interview question. Given a string s, return the length of the longest substring in which no character appears more than once. Below are examples, the constraints and 3 hints; press Practice and Dana, the interviewer, asks it out loud while you answer in TypeScript, Python, Java, C++ or Go.

Updated · By InterviewMind

Practice this question

Free in your browser, no account.

The problem

Coding · Medium

Given a string s, return the length of the longest substring in which no character appears more than once.

A substring is a run of characters that sit next to each other in s. Characters picked from different places don’t count.

Example 1

Inputs = "banana"Output3

“ban” has no repeated character, and every longer substring does.

Example 2

Inputs = "aaaa"Output1

Example 3

Inputs = "dvdf"Output3

The answer is “vdf”. When the second d arrives, the run can keep the v rather than start over.

Constraints

  • 0 ≤ s.length ≤ 5 · 10⁴
  • s holds English letters, digits, symbols and spaces

Hints

Open one at a time, and try the question again after each.

Hint 1

Picture a window sliding along the string. Grow it on the right one character at a time, and shrink it from the left only when the new character is already inside.

Hint 2

Remember where you last saw each character, in a hash map or an array indexed by character code. On a repeat, jump the window’s left edge to just past that last sighting instead of stepping one at a time.

Hint 3

Never move the left edge backward: in “abba”, when the last a arrives, the first a sits before the window’s start, so it isn’t a repeat. And an empty string has an answer of 0.

Practice it out loud

In the practice room Dana reads the question aloud in your browser’s own voice, with captions, and you answer in the editor beside it, in TypeScript, Python, Java, C++ or Go. It can look like LeetCode, HackerRank, CoderPad or Codility, so the screen is the one you’ll meet. It’s free and needs no account. Run the InterviewMind desktop app beside it and it hears the question the way it hears a real call, so you can see what it would show you in the live round.

Practice this question

More coding questions

More on these rounds: Coding interview practice.

interviewmind

Clarity under pressure.

Download for macOSWindows

On an Intel Mac? Download for Intel