Counting matching substrings in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a string, str, as the first argument, and an array of strings, arr, as the second argument. Our function should count and return the number of arr[i] that is a subsequence of string str.

For example, if the input to the function is

Input

const str = 'klmnop';
const arr = ['k', 'll', 'klp', 'klo'];

Output

const output = 3;

Output Explanation

Because the required strings are ‘k’, ‘klp’, and ‘klo’

Example

Following is the code −

 Live Demo

const str = 'klmnop';
const arr = ['k', 'll', 'klp', 'klo'];
const countSubstrings = (str = '', arr = []) => {
   const map = arr.reduce((acc, val, ind) => {
      const c = val[0]
      acc[c] = acc[c] || []
      acc[c].push([ind, 0])
      return acc
   }, {})
   let num = 0
   for (let i = 0; i < str.length; i++) {
      if (map[str[i]] !== undefined) {
         const list = map[str[i]]
         map[str[i]] = undefined
         list.forEach(([wordIndex, charIndex]) => {
            if (charIndex === arr[wordIndex].length - 1) {
               num += 1
            } else {
               const nextChar = arr[wordIndex][charIndex + 1]
               map[nextChar] = map[nextChar] || []
               map[nextChar].push([wordIndex, charIndex + 1])
            }  
         })
      }
   }
   return num
}
console.log(countSubstrings(str, arr));

Output

3
raja
Published on 24-Apr-2021 13:26:19
Advertisements