Skip to content
Learn Netverks
Company prep X (Twitter)
Junior (1–3 years) Coding / DSA Medium

Find the length of the longest substring without repeating characters

Reported in X (Twitter) USA engineering loops. Sliding window pattern for substring problems with hash set or map tracking.

Role
SDE
Location
San Jose, CA
Study track
JavaScript

Often asked in X (Twitter) 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.

Try answering aloud first

Cover trade-offs, structure, and a concrete example before revealing the baseline response.

Spoiler-free prep mode

How to frame this at X (Twitter): 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.

Comments (0)

Share how this question came up in your loop, or add tips for others preparing.

Log in to comment on this question.