23. Longest Substring Without Repeating Characters
mediumAsked at QuoraFind 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^4s consists of English letters, digits, symbols, and spaces
Examples
Example 1
s = "abcabcbb"3Explanation: "abc" is the longest substring without repeating characters.
Example 2
s = "bbbbb"1Approaches
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.
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 →