Check whether we can form string2 by deleting some characters from string1 without reordering the characters of any string - JavaScript



We are required to write a JavaScript function that takes in two strings let’s say str1 and str2 as the first and the second argument.

The function should determine whether we can form str2 by deleting some characters from str1, without reordering the characters of any string.

For example −

If the two strings are −

const str1 = 'sjkfampeflef';
const str2 = 'sample';

Then the output should be true because we can form str2 by deleting some characters from str1.

Example

Following is the code −

const str1 = 'sjkfampeflef';
const str2 = 'sample';
const checkConvertibility = (str1 = '', str2 = '') => {
   if(!str1 || !str2){
      return false;
   };
   const strArr1 = str1.split('');
   const strArr2 = str2.split('');
   const shorter = strArr1.length < strArr2.length ? strArr1 : strArr2;
   const longer = strArr1.length < strArr2.length ? strArr2 : strArr1;
   for(let i = 0; i < shorter.length; i++){
      const el = shorter[i];
      const index = longer.indexOf(el);
      if(index !== -1){
         longer.splice(index, 1);
         continue;
      };
      return false;
   };
   return true;
};
console.log(checkConvertibility(str1, str2));

Output

And the output in the console will be −

true

Advertisements