Skip to main content

23. Longest Substring Without Repeating Characters

mediumAsked at Quora

Find the longest contiguous substring with all unique characters — Quora's query-normalisation step applies this sliding-window pattern to extract the longest non-repetitive token sequence from user search strings.

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

Problem

Given a string s, find the length of the longest substring without duplicate 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

Explanation: "abc" is the longest substring without repeating characters.

Example 2

Input
s = "bbbbb"
Output
1

Approaches

1. Brute force

Check every substring for uniqueness using a Set.

Time
O(n^3)
Space
O(min(n, m))
function lengthOfLongestSubstring(s) {
  let max = 0;
  for (let i = 0; i < s.length; i++) {
    const seen = new Set();
    for (let j = i; j < s.length; j++) {
      if (seen.has(s[j])) break;
      seen.add(s[j]);
      max = Math.max(max, j - i + 1);
    }
  }
  return max;
}

Tradeoff:

2. Sliding window with last-seen index map

Maintain a window [left, right]. Store the last seen index of each character. When a duplicate is found, jump left past the duplicate's previous position without re-scanning.

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

Tradeoff:

Quora-specific tips

Quora uses this as a calibration problem — they expect you to reach for the index-map variant rather than a Set, because jumping left in O(1) matters when the alphabet is large. Mention that the `>= left` guard prevents stale map entries from shrinking the window.

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 Quora interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →