23. Longest Substring Without Repeating Characters
mediumAsked at BookingFind 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^4s consists of English letters, digits, symbols and spaces
Examples
Example 1
s = "abcabcbb"3Explanation: The answer is 'abc', with length 3.
Example 2
s = "bbbbb"1Example 3
s = "pwwkew"3Approaches
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.
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 →