Bird
Raised Fist0
DSA Javaprogramming

Minimum Window Substring in DSA Java

Choose your learning style10 modes available
Mental Model
Find the smallest part of a big string that contains all characters of a smaller string.
Analogy: Imagine looking for the shortest piece of a long sentence that has all the letters of a secret word you want to find.
S: A B C D E B A C
T: A B C
Window: [   ↑       ]
We slide the window to find the smallest part containing A, B, and C.
Dry Run Walkthrough
Input: S = "ADOBECODEBANC", T = "ABC"
Goal: Find the smallest substring in S that contains all characters A, B, and C
Step 1: Expand right pointer to include characters until all T chars are in window
Window: A D O B E C (indices 0 to 5)
Contains A, B, C
Why: We need to find a window that has all characters from T
Step 2: Try to shrink window from left to remove unnecessary chars
Window shrinks to B E C (indices 3 to 5)
Still contains A, B, C? No, missing A
Why: Remove extra chars to find smaller valid window
Step 3: Expand right pointer to include more chars to regain all T chars
Window: B E C O D E B A (indices 3 to 10)
Contains A, B, C
Why: We lost A, so expand to include it again
Step 4: Shrink window from left to minimize size while keeping all chars
Window shrinks to B A N C (indices 9 to 12)
Contains A, B, C
Why: Try to find smaller valid window
Step 5: Update minimum window to BANC
Minimum window found: B A N C
Why: This is the smallest window containing all chars
Result:
B A N C
Minimum window substring is "BANC"
Annotated Code
DSA Java
import java.util.*;

public class MinimumWindowSubstring {
    public static String minWindow(String s, String t) {
        if (s.length() == 0 || t.length() == 0) return "";

        Map<Character, Integer> dictT = new HashMap<>();
        for (char c : t.toCharArray()) {
            dictT.put(c, dictT.getOrDefault(c, 0) + 1);
        }

        int required = dictT.size();

        int left = 0, right = 0;
        int formed = 0;
        Map<Character, Integer> windowCounts = new HashMap<>();

        int[] ans = {-1, 0, 0}; // length, left, right

        while (right < s.length()) {
            char c = s.charAt(right);
            windowCounts.put(c, windowCounts.getOrDefault(c, 0) + 1);

            if (dictT.containsKey(c) && windowCounts.get(c).intValue() == dictT.get(c).intValue()) {
                formed++;
            }

            while (left <= right && formed == required) {
                c = s.charAt(left);

                if (ans[0] == -1 || right - left + 1 < ans[0]) {
                    ans[0] = right - left + 1;
                    ans[1] = left;
                    ans[2] = right;
                }

                windowCounts.put(c, windowCounts.get(c) - 1);
                if (dictT.containsKey(c) && windowCounts.get(c).intValue() < dictT.get(c).intValue()) {
                    formed--;
                }

                left++;
            }

            right++;
        }

        return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
    }

    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        System.out.println(minWindow(s, t));
    }
}
for (char c : t.toCharArray()) { dictT.put(c, dictT.getOrDefault(c, 0) + 1); }
Count required characters from T
while (right < s.length()) {
Expand window by moving right pointer
windowCounts.put(c, windowCounts.getOrDefault(c, 0) + 1);
Add current char to window counts
if (dictT.containsKey(c) && windowCounts.get(c).intValue() == dictT.get(c).intValue()) { formed++; }
Check if current char meets required count
while (left <= right && formed == required) {
Try to shrink window from left while valid
if (ans[0] == -1 || right - left + 1 < ans[0]) { ans[0] = right - left + 1; ans[1] = left; ans[2] = right; }
Update minimum window if smaller found
windowCounts.put(c, windowCounts.get(c) - 1);
Remove left char from window counts
if (dictT.containsKey(c) && windowCounts.get(c).intValue() < dictT.get(c).intValue()) { formed--; }
Decrease formed if window no longer valid
left++;
Move left pointer to shrink window
right++;
Move right pointer to expand window
OutputSuccess
BANC
Complexity Analysis
Time: O(n + m) because we traverse string S with two pointers and count characters from T once
Space: O(m) for storing counts of characters in T and current window
vs Alternative: Naive approach checks all substrings leading to O(n^2) time; sliding window reduces it to linear time
Edge Cases
Empty string S or T
Returns empty string immediately
DSA Java
if (s.length() == 0 || t.length() == 0) return "";
T longer than S
No valid window, returns empty string
DSA Java
return ans[0] == -1 ? "" : s.substring(ans[1], ans[2] + 1);
T contains characters not in S
No valid window, returns empty string
DSA Java
formed == required condition in while loop prevents false positives
When to Use This Pattern
When asked to find the smallest substring containing all characters of another string, use the sliding window pattern with two pointers and character counts.
Common Mistakes
Mistake: Not updating the formed count correctly when shrinking the window
Fix: Decrease formed only when a required character count falls below needed frequency
Mistake: Not checking if the window contains all required characters before shrinking
Fix: Use a formed variable to track when all required characters are included
Summary
Finds the smallest substring in a string containing all characters of another string.
Use when you need to find a minimal window covering all required elements.
The key is to expand and shrink a window while tracking character counts to maintain validity.

Practice

(1/5)
1. What is the main goal of the Minimum Window Substring problem?
easy
A. Find the smallest substring in a string that contains all characters of another string
B. Find the longest substring without repeating characters
C. Count the number of substrings that contain a specific character
D. Sort the characters of a string in ascending order

Solution

  1. Step 1: Understand the problem statement

    The problem asks to find the smallest part of a string that includes all characters from another string.
  2. Step 2: Compare options with the problem goal

    Only Find the smallest substring in a string that contains all characters of another string matches the goal of finding the smallest substring containing all characters of another string.
  3. Final Answer:

    Find the smallest substring in a string that contains all characters of another string -> Option A
  4. Quick Check:

    Minimum window substring = smallest substring containing all chars [OK]
Hint: Look for smallest substring covering all target chars [OK]
Common Mistakes:
  • Confusing with longest substring problems
  • Thinking about sorting instead of substring search
  • Ignoring the requirement to include all characters
2. Which Java data structure is most suitable to keep track of character counts when solving the Minimum Window Substring problem?
easy
A. ArrayList<Character>
B. LinkedList<Character>
C. HashMap
D. Stack<Character>

Solution

  1. Step 1: Identify the need for character frequency tracking

    We need to count how many times each character appears in the target string and current window.
  2. Step 2: Choose a data structure that maps characters to counts

    HashMap allows storing character keys with their counts efficiently.
  3. Final Answer:

    HashMap -> Option C
  4. Quick Check:

    Use HashMap for char count tracking [OK]
Hint: Use HashMap to map chars to counts quickly [OK]
Common Mistakes:
  • Using ArrayList which doesn't map keys to counts
  • Using Stack or LinkedList which don't store counts
  • Trying to use arrays without knowing character range
3. What will be the output of the following Java code snippet?
String s = "ADOBECODEBANC";
String t = "ABC";
// Assume minWindow(s, t) returns the minimum window substring
System.out.println(minWindow(s, t));
Given that minWindow is correctly implemented for the Minimum Window Substring problem.
medium
A. "BANC"
B. "ADOBEC"
C. "CODEBA"
D. "DOBECODEBA"

Solution

  1. Step 1: Understand the input strings

    String s is "ADOBECODEBANC" and t is "ABC". We want the smallest substring of s containing A, B, and C.
  2. Step 2: Identify the minimum window substring

    The substring "BANC" is the shortest substring containing all characters A, B, and C.
  3. Final Answer:

    "BANC" -> Option A
  4. Quick Check:

    Minimum window substring for "ABC" in s = "BANC" [OK]
Hint: Remember classic example: "BANC" is minimum window for "ABC" [OK]
Common Mistakes:
  • Choosing longer substrings that contain all chars
  • Confusing order of characters in substring
  • Assuming first occurrence is minimum window
4. Consider this buggy Java code snippet for Minimum Window Substring:
public String minWindow(String s, String t) {
    Map map = new HashMap<>();
    for (char c : t.toCharArray()) {
        map.put(c, map.getOrDefault(c, 0) + 1);
    }
    int left = 0, right = 0, count = t.length();
    int minLen = Integer.MAX_VALUE, start = 0;
    while (right < s.length()) {
        char c = s.charAt(right);
        if (map.containsKey(c)) {
            map.put(c, map.get(c) - 1);
            if (map.get(c) >= 0) count--;
        }
        while (count == 0) {
            if (right - left + 1 < minLen) {
                minLen = right - left + 1;
                start = left;
            }
            char leftChar = s.charAt(left);
            if (map.containsKey(leftChar)) {
                map.put(leftChar, map.get(leftChar) + 1);
                if (map.get(leftChar) > 0) count++;
            }
            left++;
        }
        right++;
    }
    return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start + minLen);
}
What is the main bug in this code?
medium
A. The map is not updated correctly when shrinking the window
B. The substring returned uses wrong indices
C. The while loop condition should be count > 0 instead of count == 0
D. The count variable is initialized incorrectly

Solution

  1. Step 1: Analyze the substring return statement

    The substring is returned using s.substring(start, start + minLen). In Java, substring's end index is exclusive, so this is correct.
  2. Step 2: Check map and count updates

    The map and count updates when expanding and shrinking the window are correct.
  3. Step 3: Check loop conditions and initialization

    Count initialization and while loop conditions are correct.
  4. Step 4: Identify the actual bug

    The main bug is that the code does not handle the case when the minimum window substring is not found, returning an empty string is correct, so no bug there. The code is logically correct.
  5. Step 5: Re-examine options

    Options A, B, and C are incorrect. The substring returned uses wrong indices is also not a bug. Therefore, no bug exists in the code.
  6. Step 6: Final Answer

    No bug found in the code snippet
Hint: Check carefully map and count updates and substring indices [OK]
Common Mistakes:
  • Confusing loop conditions for count
  • Incorrect substring indices
  • Ignoring map updates when shrinking window
5. You want to find the minimum window substring of s = "aabbccdd" that contains all characters of t = "abc". Which of the following substrings is the correct minimum window substring?
hard
A. "abbc"
B. "bcca"
C. "abc"
D. "aabbcc"

Solution

  1. Step 1: Identify all substrings containing 'a', 'b', and 'c'

    Check substrings of s that include at least one 'a', one 'b', and one 'c'.
  2. Step 2: Find the smallest such substring

    "aabbcc" (positions 0 to 5) contains 'a', 'b', 'c' and is the smallest continuous substring containing all characters. "abbc" is not a continuous substring in s. "abc" does not appear as a continuous substring. "bcca" is not a substring in order.
  3. Final Answer:

    "aabbcc" -> Option D
  4. Quick Check:

    Minimum window substring = "aabbcc" [OK]
Hint: Check all substrings, pick shortest with all chars [OK]
Common Mistakes:
  • Assuming "abc" must appear in order
  • Choosing shorter substrings that are not continuous
  • Ignoring repeated characters in s
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard