Minimum Window Subsequence in C++


Suppose we have two strings S and T, we have to find the minimum substring W of S, so that T is a subsequence of W. If there is no such window in S that covers all characters in T, then return empty string. If there are multiple such windows, we have to return the one with the left-most starting index.

So, if the input is like S = "abcdebdde", T = "bde", then the output will be "bcde" as it occurs before "bdde". "deb" is not a smaller window because the elements of T in the window must occur in order.

To solve this, we will follow these steps −

  • tidx := 0, tlen := size of T

  • n := size of S

  • i := 0, length := inf, start := -1

  • while i < n, do −

    • if S[i] is same as T[tidx], then −

      • (increase tidx by 1)

      • if tidx is same as tlen, then −

        • end := i + 1

        • (decrease tidx by 1)

        • while tidx >= 0, do −

          • if S[i] is same as T[tidx], then −

            • (decrease tidx by 1)

          • (decrease i by 1)

        • (increase i by 1)

        • (increase tidx by 1)

        • if end - i < length, then −

          • length := end - i

          • start := i

    • (increase i by 1)

  • if start is not equal to -1, then −

    • for initialize i := start, when i < start + length, update (increase i by 1), do −

      • ret := ret + S[i]

  • return ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   string minWindow(string S, string T) {
      int tidx = 0;
      int tlen = T.size();
      int n = S.size();
      int i = 0;
      int length = INT_MAX;
      int start = -1;
      string ret;
      while (i < n) {
         if (S[i] == T[tidx]) {
            tidx++;
            if (tidx == tlen) {
               int end = i + 1;
               tidx--;
               while (tidx >= 0) {
                  if (S[i] == T[tidx]) {
                     tidx--;
                  }
                  i--;
               }
               i++;
               tidx++;
               if (end - i < length) {
                  length = end - i;
                  start = i;
               }
            }
         }
         i++;
      }
      if (start != -1)
      for (int i = start; i < start + length; i++)
      ret += S[i];
      return ret;
   }
};
main(){
   Solution ob;
   cout << (ob.minWindow("abcdebdde", "bde"));
}

Input

"abcdebdde", "bde"

Output

"bcde"

Updated on: 11-Jul-2020

805 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements