14. Longest Substring Without Repeating Characters
mediumAsked at RampFind the length of the longest substring with all unique characters.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s, find the length of the longest substring without repeating characters. A substring is a contiguous sequence of characters.
Constraints
0 <= s.length <= 5 * 10^4s consists of English letters, digits, symbols and spaces
Examples
Example 1
s = "abcabcbb"3Example 2
s = "pwwkew"3Approaches
1. Brute force
Check every substring for uniqueness using a set.
- Time
- O(n^3)
- Space
- O(n)
function lengthOfLongestSubstring(s) {
let best = 0;
for (let i = 0; i < s.length; i++) {
const seen = new Set();
for (let j = i; j < s.length && !seen.has(s[j]); j++) {
seen.add(s[j]);
best = Math.max(best, j - i + 1);
}
}
return best;
}Tradeoff:
2. Sliding window with last-seen map
Track the last index each character was seen; when a duplicate falls inside the window, jump the left pointer past it.
- Time
- O(n)
- Space
- O(k)
function lengthOfLongestSubstring(s) {
const last = new Map();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
const c = s[right];
if (last.has(c) && last.get(c) >= left) left = last.get(c) + 1;
last.set(c, right);
best = Math.max(best, right - left + 1);
}
return best;
}Tradeoff:
Ramp-specific tips
Ramp uses sliding-window patterns inside their fraud-detection layer to spot duplicate-card runs without scanning the full transaction log; signaling you understand last-seen pruning earns bonus.
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 Ramp interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →