Minimum Window Substring Problem

Minimum Window Substring Problem

Minimum Window Substring Problem Statement

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

Example One

{
"s": "AYZABOBECODXBANC",
"t": "ABC"
}

Output:

"BANC"

The minimum window is "BANC", which contains all letters – 'A' 'B' and 'C'. We cannot find a window of smaller length than "BANC".

Example Two

{
"s": "BACRDESDFBAER",
"t": "BAR"
}

Output:

"BACR"

Here, we can see that there are 2 smallest windows – "BACR" and "BAER". However, the output is "BACR" because it is the leftmost one.

Notes

  • If no such window exists, return an empty string "".
  • If there are multiple minimum windows of the same length, return the leftmost window.

Constraints:

  • 1 <= length of s <= 100000
  • 1 <= length of t <= 100000

We provided two solutions. We will refer to the length of s as n and length of t as m.

Minimum Window Substring Solution 1: Brute Force

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(n3).

As we are checking for all substrings and as there are O(n2) substrings and we take O(n) time to check whether the particular substring can be a valid window, so total complexity is O(n3).

Auxiliary Space Used

O(1).

We create frequency arrays of size 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).

For storing input it will take O(n + m), as we are storing two strings of length n and length m and the auxiliary space used is O(1) hence 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 the input string containing any ASCII characters.

Code For Minimum Window Substring Solution 1: Brute Force

    /*
    * Asymptotic complexity in terms of length of `s` `n` and length of `t` `m`:
    * Time: O(n^3).
    * Auxiliary space: O(1).
    * Total space: O(n + m).
    */

    static String minimum_window(String s, String t){
        String result = "";

        if(t.length() > s.length()) {
            return "";
        }

        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 < t.length(); i++) {
            freq1[(int)t.charAt(i)]++;
        }
        int len = n + 1;

        //looping over every substring of string s
        for(int i = 0; i < n; i++){
            for(int j = i; j < n; j++){
                int freq2[] = new int[128]; //creating a frequency array to store the frequencies of the characters in the substring
                for(int k = i; k <= j; k++){
                    freq2[s.charAt(k)]++;
                }
                //checking if a substring contains all the letters in string t
                for(int k = 0; k < 128; k++){
                    if(freq2[k] < freq1[k]) {
                        break;
                    }
                    if(k == 127){
                        // if the substring contains all the characters, we check if it can
                        // become the smallest one and update the result accordingly
                        if(len > (j - i)){
                            len = j - i;
                            result = s.substring(i, j + 1);
                        }
                    }
                }
            }
        }
        return (result.length() == 0 ? "" : result);
    }

Minimum Window Substring Solution 2: Optimal

In this approach, we create an array named frequency to keep a count of occurrences of each character in string 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 whether it can become the minimum window, and the answer is updated accordingly.

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

Time Complexity

O(n).

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

Auxiliary Space Used

O(1).

We are creating 2 frequency arrays of size 128, hence it is O(1).

Space Complexity

O(n + m).

For storing input it will take O(n + m), as we are storing two strings of length n and length m and the auxiliary space used is O(1) hence 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 the input string containing any ASCII characters.

Code For Minimum Window Substring Solution 2: Optimal

    /*
    * Asymptotic complexity in terms of length of `s` `n` and length of `t` `m`:
    * Time: O(n).
    * Auxiliary space: O(1).
    * Total space: O(n + m).
    */

    static String minimum_window(String s, String t){
        String result = "";

        if(t.length() > s.length()) {
            return "";
        }

        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 ? "" : result);
    }

We hope that these solutions to the 4 sum problem have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.

If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.

Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.

We offer 18 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:

‍To learn more, register for the FREE webinar.

Try yourself in the Editor

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

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Agentic AI

Learn to build AI agents to automate your repetitive workflows

Switch to AI/ML

Upskill yourself with AI and Machine learning skills

Interview Prep

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary