Skip to main content

32. Longest Substring Without Repeating Characters

mediumAsked at Ola

Find the length of the longest substring without repeating characters.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s, find the length of the longest substring without repeating characters.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces

Examples

Example 1

Input
s = "abcabcbb"
Output
3

Example 2

Input
s = "bbbbb"
Output
1

Approaches

1. All substrings

Enumerate every substring and check uniqueness with a set.

Time
O(n^3)
Space
O(n)
let best = 0;
for (let i=0;i<s.length;i++)
  for (let j=i;j<s.length;j++) {
    if (new Set(s.slice(i,j+1)).size === j-i+1) best = Math.max(best, j-i+1);
  }
return best;

Tradeoff:

2. Sliding window

Expand right; when a duplicate appears jump left to the last index of that char + 1. O(n) time.

Time
O(n)
Space
O(min(n, alphabet))
function lengthOfLongestSubstring(s) {
  const last = new Map();
  let left = 0, best = 0;
  for (let r = 0; r < s.length; r++) {
    if (last.has(s[r]) && last.get(s[r]) >= left) left = last.get(s[r]) + 1;
    last.set(s[r], r);
    best = Math.max(best, r - left + 1);
  }
  return best;
}

Tradeoff:

Ola-specific tips

Ola tests sliding-window discipline; tie it to bounding the longest streak of unique driver-ids passing through a dispatch hop.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Longest Substring Without Repeating Characters and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →