Min window substring in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in two strings let's call them str1 and str2.

The size of str1 is guaranteed to be greater than that of str2. We are required to find the smallest substring in str1 that contains all the characters contained in str2.

For example −

If the input strings are −

const str1 = 'abcdefgh';
const str2 = 'gedcf';

Then the output should be −

const output = 'cdefg';

because this the smallest consecutive substring of str1 that contains all characters of str2.

Example

Following is the code −

const str1 = 'abcdefgh';
const str2 = 'gedcf';
const subIncludesAll = (str, str2) => {
   for (let i = 0; i < str.length; i++) {
      if (str2.indexOf(str[i]) !== -1) {
         str2 = str2.replace(str[i], '');
      };
   };
   return (str2.length === 0);
};
const minWindow = (str1 = '', str2 = '') => {
   let shortestString = null;
   for (let i = 0; i < str1.length; i++) {
      for (let j = i; j < str1.length; j++) {
         let testString = str1.substr(i, j-i+1);
         if (subIncludesAll(testString, str2)) {
            if (shortestString === null || testString.length < shortestString.length) {
               shortestString = testString;
            }
         }
      }
   }
   return shortestString;
};
console.log(minWindow(str1, str2));

Output

Following is the output on console −

cdefg
raja
Published on 11-Dec-2020 09:27:36
Advertisements