About usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career

Minimum Window Substring Problem

You are given alphanumeric strings, s and t. Find the minimum window (substring) in s that contains all the characters of t.

Example One:

Input:

AYZABOBECODXBANC

ABC

Output: BANC

The minimum window is "BANC," which contains all letters, A, B, and C, from the second string. There is no window smaller than “BANC.”

Example Two:

Input:

BACRDESDFBAER

BAR

Output: BACR

Here, we can see that there are two smallest windows — “BACR” and “BAER.” However, the output is “BACR” because it is the leftmost window.

Notes:

Input Parameters: There are two arguments in the input — a string named s and a string named t

Output: Return a string result, which is the minimum window (substring) in string s that contains all characters of string t. If no such window exists, then return “-1” (string). If there are multiple minimum windows of the same length, then return the leftmost window.

Constraints:

  • 1 <= length(s) <= 100000
  • 1 <= length(t) <= 100000

Solutions 1: Brute Force (brute_force_solution.java)

This is a brute force approach. We check whether each substring of string s is a valid window or not. If we find it to be a valid window, we update our result accordingly. 

Time Complexity:

O(n^3), where n is the length of string s

We are checking for all substrings, and there are O(n^2) substrings. We take O(n) time to check whether the particular substring can be a valid window. So total complexity is O(n^3).

Auxiliary Space Used:

O(1)

We create frequency arrays of size O(128) to count the occurrence of each character present in strings t and s. So overall complexity is O(1).

Space Complexity:

O(n+m) where n is the length of string s and m is the length of string t

It will take O(n+m) for storing input, as we are storing two strings of length n and length m. The auxiliary space used is O(1). Hence, the total complexity will be O(n+m).

Note: We could use an array of length 62 (with some mapping) instead of 128, but this is a general solution, which works for an input string containing any ASCII characters.


// -------- START --------
    public static String minimum_window(String s, String t){
        
        String result = "";

        if(t.length()>s.length()) {
            return "-1";
        }
        
        int freq1[] = new int[128]; //creating a frequency array to store the frequencies of the characters in string t
        int n = s.length();
        for(int i=0;i(j-i)){
                            len = j-i;
                            result = s.substring(i,j+1);
                        }
                    }
                }
            }
        }
        return result.length()==0?"-1":result;
    }
    // -------- END --------


Solution 2: Optimal solution (optimal_solution.java)

In this approach, we create an array named frequency to keep a count of occurrences of each character in string t [O(length of t)]. Now, we start traversing the string s and keep a variable cnt, which increases whenever we encounter a character present in string t

When the value of count reaches the length of t, this substring contains all the characters present in string t. We try removing extra characters as well as unwanted characters from the beginning of the obtained string. The resultant string is checked to see if it is a minimum window, and the answer is updated accordingly.

This algorithm uses the two-pointer method, which is widely used in solving various problems. 

Time Complexity:

O(n), where n is the length of string s

Since each character of string s is traversed at most twice, the algorithm’s time complexity is O(n) + O(m).

Auxiliary Space Used:

O(1)

We are creating two frequency arrays, each of size 128, which use extra space O(128) + O(128). Hence, the auxiliary space used is O(1).

Space Complexity:

O(n+m), where n is the length of string s and m is the length of string t

It will take O(n+m) for storing input, as we are storing two strings of length n and length m, and the auxiliary space used is O(1). Hence, the total complexity will be O(n+m).

Note: We could use an array of length 62 (with some mapping) instead of 128, but this is a general solution, which works for an input string containing any ASCII characters.


// -------- START --------
    public static String minimum_window(String s, String t){

        String result = "";

        if(t.length()>s.length()) {
            return "-1";
        }
        int n = s.length(), m = t.length();   
        int freq1[] = new int[128]; /*creating a frequency array to store the 
                                    frequencies of the characters in string t*/
        int freq2[] = new int[128]; /*creating a frequency array to store the 
                                    frequencies of the characters in string s*/
        for (char c : t.toCharArray()) {
            freq1[c]++;
        }
        int l = 0, len = n+1; 
        int cnt = 0;
        /*This part uses "2 pointer method." You can find a link 
        for the same in the editorial of this problem.*/
        for (int i = 0; i < n ; i++){
            char temp = s.charAt(i);
            freq2[temp]++;
            //if a character is present in string t we increment the count of cnt variable.
            if (freq1[temp]!=0 && freq2[temp]<=freq1[temp]) {
                cnt++; 
            }
            /*if we match all the characters present in string t, 
            we try to find the minimum window possible*/
            if (cnt==m) {
                /*if any character is occuring more than the required times, we try to remove it
                from the starting and also try to remove the unwanted characters that are 
                not a part of string t from the starting. We check the remainder string if it 
                can become the smallest window.*/
                while (freq2[s.charAt(l)]>freq1[s.charAt(l)] || freq1[s.charAt(l)]==0) { 
                    if (freq2[s.charAt(l)]>freq1[s.charAt(l)]) { 
                        freq2[s.charAt(l)]--; 
                    }
                    l++; 
                }
                //check if this can become the smallest window and update the result accordingly.
                if (len > i-l+1) { 
                    len = i-l+1;
                    result = s.substring(l,l+len);
                } 
            } 
        } 
        return result.length()==0?"-1":result;
    }
    // -------- END --------


Try yourself in the Editor

Note: Input and Output will already be taken care of.

Recommended Posts

All Posts