Skip to main content

23. Longest Substring Without Repeating Characters

mediumAsked at Booking

Find the longest window of unique characters in a string — Booking's content team uses a similar sliding-window approach to detect duplicate tokens in property descriptions and enforce uniqueness constraints on hotel name fragments.

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

Explanation: The answer is 'abc', with length 3.

Example 2

Input
s = "bbbbb"
Output
1

Example 3

Input
s = "pwwkew"
Output
3

Approaches

1. Brute force

Check every substring for uniqueness using a Set.

Time
O(n^3)
Space
O(min(n, charset))
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 index map

Track last seen index of each character. When a duplicate is found, jump left pointer past the previous occurrence. O(n) single pass.

Time
O(n)
Space
O(min(n, charset))
function lengthOfLongestSubstring(s) {
  const lastSeen = new Map();
  let left = 0;
  let max = 0;

  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    if (lastSeen.has(ch) && lastSeen.get(ch) >= left) {
      left = lastSeen.get(ch) + 1;
    }
    lastSeen.set(ch, right);
    max = Math.max(max, right - left + 1);
  }

  return max;
}

Tradeoff:

Booking-specific tips

Booking interviewers often extend this to 'at most K distinct characters' — the same index-map technique generalizes cleanly. Showing you anticipate that variant signals strong pattern awareness.

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

Practice these live with InterviewChamp.AI →