All coding questions

Longest Substring Without Repeating Characters

medium
Blind 75NeetCode 150stringssliding-windowhashing

Problem

Given a string, find the length of the longest contiguous substring that contains no repeated character.

Examples

Input: s = "abcabcbb"
Output: 3
The substring "abc" has length three.
Input: s = "bbbbb"
Output: 1
Only a single character can be in the window.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • String contains printable ASCII characters
Hints(tap to reveal)
  • 1. Grow a window and shrink it when a repeat appears.
  • 2. Remember the last index of each character.
Optimal approach(spoiler)
  1. Maintain a sliding window with a left and right boundary.
  2. Store the most recent index of each character.
  3. When the current character was seen inside the window, jump the left boundary past it.
  4. Update the best window length at each step.
  5. O(n) time, O(min(n, alphabet)) space.

Ready to solve it?

Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.

Practice in the editor