Skip to main content

15. Longest Substring Without Repeating Characters

mediumAsked at MercadoLibre

Find the length of the longest contiguous substring without repeated characters.

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

Problem

Given a string s, find the length of the longest substring that contains no duplicate characters. The substring must be contiguous.

Constraints

  • 0 <= s.length <= 5 * 10^4
  • s may contain any ASCII characters

Examples

Example 1

Input
s = "abcabcbb"
Output
3

Example 2

Input
s = "bbbbb"
Output
1

Approaches

1. Brute force

Try every substring and check uniqueness with a set.

Time
O(n^3)
Space
O(n)
let best = 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) best = Math.max(best, j-i+1);
  }
return best;

Tradeoff:

2. Sliding window with index map

Walk a right pointer; when we hit a duplicate inside the window, jump left to one past the last sighting.

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:

MercadoLibre-specific tips

MercadoLibre search-quality engineers use this to test sliding-window thinking — exactly the pattern they apply to dedupe user search-query streams before sending them to the relevance pipeline.

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

Practice these live with InterviewChamp.AI →