← Microsoft bank

Microsoft · Question 15 · Strings

Longest Substring Without Repeating Characters

StringsJavacode⏱ O(n)💾 O(min(m,n))
Product-based

Problem

Find the length of the longest substring without repeating characters.

Approach

Slide a window with last-seen indices, jumping past repeats.

Time O(n)Space O(min(m,n))

How it works

  1. 1Remember each character's latest index.
  2. 2Jump the window start past in-window repeats.

Sample input / output

Input:
abcabcbb
Output:
3

Constraints

0 <= s.length <= 5 * 10^4.

Solution — read it, then walk it

Time O(n)Space O(min(m,n))Loops 1Branches 1Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
yesno↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static intlengthOfLongestSubstring(Strings)HashMap<Character, Integer>map = new HashMap<>()DEFINE left = 0, maxLen = 0for (int right = 0;right < s.length();right++)DEFINE c = s.charAt(right)if(map.containsKey(c))left = Math.max(map.get(c)+ 1, left)map.put(c, right)maxLen = Math.max(maxLen,right - left + 1)RETURN maxLenDEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)String s = sc.next()System.out.println(lengthOfLongestSubstring(s))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/17

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits