Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string "".

The testcases will be generated such that the answer is unique.

Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
Explanation: The minimum window substring "BANC" includes 'A', 'B', and 'C' from string t.
Input: s = "a", t = "a"
Output: "a"
Explanation: The entire string s is the minimum window.
Input: s = "a", t = "aa"
Output: ""
Explanation: Both 'a's from t must be included in the window.
Since the largest window of s only has one 'a', return empty string.
Constraints:

Follow up: Could you find an algorithm that runs in O(m + n) time?

Contents

In this approach, first we are going to capture characters in t and their count into a HashMap, then usnig sliding window technique find the shortest substring in s, which has all the characters from t and their count.

Implementation steps:
import java.util.HashMap; public class MinimumWindowSubstring { static String minWindow(String s, String t) { //first take t characters and their count into a HashMap HashMap<Character, Integer> tMap = new HashMap<>(); for(char c: t.toCharArray()) { tMap.merge(c, 1, Integer::sum); } HashMap<Character, Integer> sMap = new HashMap<>(); int left = 0; int right =0; int requiredCount = tMap.size(); int haveCount = 0; int[] ansIndices = new int[]{0,0}; int minLength = Integer.MAX_VALUE; // setting it to a maximum value since we want to find min while(right < s.length()) { char c = s.charAt(right); int sCharCount = sMap.merge(c, 1, Integer::sum); int tCharCount =tMap.getOrDefault(c, 0); if(sCharCount == tCharCount){ haveCount++; } while(haveCount == requiredCount) { if(right-left+1 <minLength) { minLength = right-left+1; ansIndices[0] = left; ansIndices[1] = right; } char leftChar = s.charAt(left++); sCharCount = sMap.merge(leftChar, -1, Integer::sum); if(tMap.containsKey(leftChar) && sCharCount < tMap.get(leftChar)) { haveCount--; } } right++; } return minLength == Integer.MAX_VALUE ? "" : s.substring(ansIndices[0], ansIndices[1]+1); } public static void main(String[] args) { System.out.println(minWindow("ADOBECODEBANC", "ABC")); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time, where n is the length of input string s.
Space complexity: O(n), since we are storing characters of input strings s and t into HashMaps.

Above implementations source code can be found at GitHub link for Java code