Minimum Window Substring in Java: Explanation & Practice

Find minimum window containing all characters of pattern

Problem summary

Given strings s and t, find the minimum window in s that contains all characters of t. Classic sliding window problem.

Starter code

public class Main {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        
        // Track required chars and their counts
        // Expand to include all required, shrink to minimize
        // Print: BANC
    }
}

Expected output and test cases

  • s=ADOBECODEBANC, t=ABC
    BANC
  • s=a, t=a
    a
  • s=a, t=aa
    No valid window

Hints

  1. Use HashMap to track required character frequencies
  2. Track how many unique chars we still need to match
  3. Expand right until we have all chars
  4. Then shrink left while still valid, updating minimum

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler