Sliding Window Longest or shortest window

170. Longest Substring Without Repeating Characters

Medium 147 DSA Sheet

You are given a string s. Return the length of the longest substring of s in which no character appears more than once.

A substring is a block of characters that sit next to each other in s. Every character counts, including spaces, digits and punctuation, and an uppercase letter is a different character from its lowercase form.

Example 1

Input: s = "programming"

Output: 5

Explanation: "ogram", from index 2 to index 6, holds five different characters. Reaching one step further on either side repeats a character: the r at index 1 or the m at index 7.

Example 2

Input: s = "bookkeeper"

Output: 3

Explanation: A substring with no repeat can hold only one letter of each pair oo, kk and ee, so every such substring is short. The longest is "per", at the end.

Example 3

Input: s = "coffee break"

Output: 6

Explanation: The space counts like any other character. " break" holds six different characters, and adding the e before it would repeat e.

Check your understanding

Work out the answer for this input before you write any code.

s = "abcbdef"

Constraints

  • 0 ≤ s.length ≤ 105
  • s holds printable ASCII characters only: letters, digits, punctuation and the space (codes 32 to 126).

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.