Skip to main content

17. Longest Substring Without Repeating Characters

mediumAsked at Coursera

Find the length of the longest substring without repeating characters, a sliding-window classic Coursera uses to evaluate string processing for search and content indexing pipelines.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s, find the length of the longest substring without repeating characters.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s consists of English letters, digits, symbols and spaces

Examples

Example 1

Input
s = "abcabcbb"
Output
3

Example 2

Input
s = "bbbbb"
Output
1

Approaches

1. Brute force (all substrings)

Check every substring for uniqueness using a Set — O(n^3) and impractical for large inputs.

Time
O(n^3)
Space
O(min(n,m))
function lengthOfLongestSubstring(s) {
  let max = 0;
  for (let i = 0; i < s.length; i++)
    for (let j = i+1; j <= s.length; j++)
      if (new Set(s.slice(i,j)).size === j-i) max = Math.max(max, j-i);
  return max;
}

Tradeoff:

2. Sliding window with Map

Maintain a window [left, right] and a Map of character → last-seen index. When a repeat is found, jump left past the previous occurrence, keeping the window duplicate-free throughout.

Time
O(n)
Space
O(min(n,m))
function lengthOfLongestSubstring(s) {
  const map = new Map();
  let left = 0, max = 0;
  for (let right = 0; right < s.length; right++) {
    const c = s[right];
    if (map.has(c) && map.get(c) >= left) {
      left = map.get(c) + 1;
    }
    map.set(c, right);
    max = Math.max(max, right - left + 1);
  }
  return max;
}

Tradeoff:

Coursera-specific tips

Coursera interviews emphasize algorithms for educational platforms, content recommendation systems, and scalable delivery pipelines. Medium-difficulty graph and DP problems are typical.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Longest Substring Without Repeating Characters and other Coursera interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →