Skip to main content

12. Longest Substring Without Repeating Characters

mediumAsked at Swiggy

Find the length of the longest substring with all distinct characters.

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

Problem

Given a string s, return the length of the longest substring whose characters are all unique. Substrings are contiguous slices of s.

Constraints

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

Examples

Example 1

Input
s='abcabcbb'
Output
3

Example 2

Input
s='bbbbb'
Output
1

Approaches

1. All substring check

Enumerate 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 last-seen map

Maintain a window [left, right] and a map from char to its last index. When a repeat is inside the window, jump left past the previous occurrence. Track max length each step.

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

Tradeoff:

Swiggy-specific tips

Swiggy uses sliding-window questions because their courier-window assignment logic uses the same pattern; verbalize the left-jump rule before coding.

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

Practice these live with InterviewChamp.AI →