Skip to main content

15. Longest Substring Without Repeating Characters

mediumAsked at Grab

Find the longest substring without repeats — Grab uses this as a sliding-window fluency check.

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 set check

Try every substring and verify 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 (allUnique(s, i, j)) best = Math.max(best, j - i + 1);

Tradeoff:

2. Sliding window with index map

Track each char's latest index; slide the left edge past any prior duplicate.

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

Tradeoff:

Grab-specific tips

Grab interviewers want the sliding-window pattern named explicitly — frame the string as a stream of in-app navigation events with no repeated routes.

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

Practice these live with InterviewChamp.AI →