Skip to main content

17. Longest Substring Without Repeating Characters

mediumAsked at Udemy

Find the length of the longest substring without repeating characters — Udemy applies the sliding-window pattern to course-title deduplication and content search.

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 non-empty sequence of characters within a string.

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

Check every substring for uniqueness using a Set — O(n^3) time.

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; j < s.length; j++) {
      if (new Set(s.slice(i, j+1)).size === j-i+1) max = Math.max(max, j-i+1);
    }
  }
  return max;
}

Tradeoff:

2. Sliding window with Map

Maintain a window [left, right]; when a duplicate appears, jump left past the previous occurrence using a character-to-index map instead of shrinking one step at a time.

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:

Udemy-specific tips

Udemy asks about e-learning recommendation systems, content search, and marketplace algorithms — balanced mix of arrays, hash maps, and dynamic programming problems.

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 Udemy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →