Minimum Window Substring in C++


Suppose we have a string S and T. We have to find the minimum window in S which will contain all the characters in T. So if the input is like “ABHDAXCVBAGTXATYCB” and T = “ABC”, then the result will be: “CVBA”.

To solve this, we will follow these steps −

  • Create one map m

  • store the frequency of x into m

  • length := size of s, left := 0, right := 0, ansLeft := 0 and ansRight := 0

  • counter := size of x, flag := false, ans := empty string

  • while height < size of s −

    • c := s[right]

    • if c is present in m, then

      • if m[c] > 0, then decrease counter by 1

      • decrease m[c] by 1

    • while counter = 0 and left <= right

      • if right – left + 1 <= length

        • length := right – left + 1

        • flag := true

        • ansLeft := left, ansRight := right

      • if left = right, then break the loop

      • c := s[left]

      • if c is present in m, then increase m[c] by 1

      • if m[c] > 0, then increase counter by 1

      • increase left by 1

    • increase right by 1

  • if flag is false, then return ans

  • otherwise for i in range ansLeft to ansRight, increase ans by s[i]

  • return ans

Example

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string minWindow(string s, string x) {
      map <char, int> m;
      for(int i =0;i<x.size();i++)m[x[i]]++;
      int length = s.size();
      int left = 0, right = 0 , ansLeft = 0, ansRight = 0;
      int counter = x.size();
      bool flag = false;
      string ans = "";
      while(right<s.size()){
         char c = s[right];
         if(m.find(c)!=m.end()){
            if(m[c]>0)counter--;
            m[c]--;
         }
         while(counter == 0 && left<=right){
            if(right-left+1 <=length){
               length = right-left+1;
               flag = true;
               ansLeft = left;
               ansRight = right;
            }
            if(left == right)break;
            c = s[left];
            if(m.find(c)!=m.end()){
               m[c]++;
               if(m[c]>0)counter++;
            }
            left++;
         }
         right++;
      }
      if(!flag)return ans;
      else
      for(int i =ansLeft;i<=ansRight;i++)ans+=s[i];
      return ans;
   }
};
main(){
   Solution ob;
   cout << (ob.minWindow("ABHDAXCVBAGTXATYCB", "ABC"));
}

Input

"ABHDAXCVBAGTXATYCB"
"ABC"

Output

CVBA

Updated on: 26-May-2020

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements