Unique substrings in circular string in JavaScript



Problem

Suppose we have a S, str. which is an infinite wraparound string of the string βˆ’

"abcdefghijklmnopqrstuvwxyz".

Therefore, S will look like this βˆ’

"...zabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd....".

We are required to write a JavaScript function that takes in str, let’s call that string str, as the only argument.

  • Our function should find out how many unique non-empty substrings of str are present in S.

  • Our function should finally return the number of different non-empty substrings of str in the string S.

For example, if the input to the function is βˆ’

const str = "zab";

Then the output should be βˆ’

const output = 6;

Output Explanation

There are six substrings "z", "a", "b", "za", "ab", "zab" of string "zab" in the string S.

Example

The code for this will be βˆ’

 Live Demo

const str = "zab";
const allSubstrings = (str = '') => {
   const dp = new Array(26).fill(0);
   dp[str.charCodeAt(0) - 97] = 1;
   maxCount = 1;
   for (let i = 1; i < str.length; i++) {
      if ((str.charCodeAt(i) - str.charCodeAt(i - 1) == 1) || (str.charCodeAt(i) - str.charCodeAt(i - 1) == -25)) {
         maxCount++;
      } else {
         maxCount = 1;
      }
      dp[str.charCodeAt(i) - 97] = Math.max(dp[str.charCodeAt(i) - 97], maxCount);
   }
   return dp.reduce((item, val) => {
      return val + item;
   })
};
console.log(allSubstrings(str));

Output

And the output in the console will be βˆ’

6
Updated on: 2021-03-04T11:26:29+05:30

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements