13. Longest Substring Without Repeating Characters
mediumAsked at SquarespaceFind the length of the longest substring of distinct characters; Squarespace uses it to test the sliding-window pattern.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s, return the length of the longest substring that contains no repeating characters. Substrings must be contiguous.
Constraints
0 <= s.length <= 5 * 10^4s consists of English letters, digits, symbols and spaces
Examples
Example 1
s="abcabcbb"3Example 2
s="bbbbb"1Approaches
1. All substrings check
Enumerate every substring and verify uniqueness with a set.
- Time
- O(n^3)
- Space
- O(n)
let best=0;
for(let i=0;i<n;i++) for(let j=i;j<n;j++){
const set=new Set(s.slice(i,j+1));
if(set.size===j-i+1) best=Math.max(best,j-i+1);
}
return best;Tradeoff:
2. Sliding window with last-seen map
Move a right pointer forward while jumping the left pointer past any prior occurrence. Linear time, alphabet-sized space.
- Time
- O(n)
- Space
- O(k)
function lengthOfLongestSubstring(s) {
const last = new Map();
let l = 0, best = 0;
for (let r = 0; r < s.length; r++) {
if (last.has(s[r]) && last.get(s[r]) >= l) l = last.get(s[r]) + 1;
last.set(s[r], r);
best = Math.max(best, r - l + 1);
}
return best;
}Tradeoff:
Squarespace-specific tips
Squarespace likes when you connect this sliding window to their rate-limited publish API that windows requests per site over a moving interval.
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 Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →