Find the length of the longest substring without repeating characters
Reported in MongoDB USA engineering loops. Sliding window pattern for substring problems with hash set or map tracking.
Interview scenario
Often asked in MongoDB on-site or virtual loops at US offices (Bay Area, Seattle, NYC, Austin, and remote US). Prepare a clear spoken answer plus key trade-offs.
Model answer
Try answering aloud first
Cover trade-offs, structure, and a concrete example before revealing the baseline response.
How to frame this at MongoDB: Connect your answer to measurable impact, clarity of thought, and trade-offs the team cares about. Below is a strong baseline response you can adapt with your own project examples.
Maintain a window [left, right] and a map of character → last index. Expand right; if char seen inside window, move left past previous occurrence. Track max window length.
function lengthOfLongestSubstring(s) {
const last = new Map();
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
const ch = s[right];
if (last.has(ch) && last.get(ch) >= left) left = last.get(ch) + 1;
last.set(ch, right);
best = Math.max(best, right - left + 1);
}
return best;
}Time O(n), space O(min(n, alphabet)). Contrast with brute force O(n²).
Related patterns: minimum window substring, at-most K distinct characters, and fixed-size window for moving averages. Emphasize invariant: window always satisfies uniqueness.
Discussion
Comments (0)
Share how this question came up in your loop, or add tips for others preparing.
Log in to comment on this question.