← Microsoft bank

Microsoft · Question 67 · Strings

Minimum Window Substring

StringsJavacode⏱ O(|S|+|T|)💾 O(|S|+|T|)
Product-based

Problem

Given strings s and t, return the minimum window in s which contains all characters of t.

Approach

Expand right to cover t, shrink left while still valid.

Time O(|S|+|T|)Space O(|S|+|T|)

How it works

  1. 1Expand right until the window covers t.
  2. 2Shrink from the left while it stays valid.
  3. 3Keep the smallest valid window seen.

Sample input / output

Input:
ADOBECODEBANC
ABC
Output:
BANC

Constraints

1 <= s, t lengths <= 10^5; English letters.

Solution — read it, then walk it

Time O(|S|+|T|)Space O(|S|+|T|)Loops 3Branches 4Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesno↻ repeatyesnoyes↻ repeat↻ repeatSTARTimport java.util.*DEFINE class MainDEFINE static StringminWindow(String s, Stringt)if (s.length() <t.length()) return ""Map<Character, Integer> map= new HashMap<>()for (char c :t.toCharArray())map.put(c,map.getOrDefault(c, 0) + 1)DEFINE start = 0, end = 0,minLen = Integer.MAX_VALUE,match = 0, minStart = 0Map<Character, Integer>window = new HashMap<>()while (end <s.length())DEFINE c = s.charAt(end++)window.put(c,window.getOrDefault(c, 0) +1)if (map.containsKey(c)&&window.get(c).intValue(…match++while (match ==map.size())if (end - start <minLen)minLen = end - startminStart = startDEFINE left =s.charAt(start++)window.put(left,window.get(left) - 1)if(map.containsKey(left)&& window.get(left) …match--RETURN minLen ==Integer.MAX_VALUE ? "" :s.substring(minStart…DEFINE static voidmain(String[] args)java.util.Scanner sc = newjava.util.Scanner(System.in)String s = sc.next();String t = sc.next()System.out.println(minWindow(s,t))END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/28

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