Finding the longest Substring with At Least n Repeating Characters in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in a string as the first argument and a positive integer n as the second argument.

The string is likely to contain some repeating characters. The function should find out and return the length of the longest substring from the original string in which all characters appear at least n number of times.

For example −

If the input string and the number are −

const str = 'kdkddj';
const num = 2;

Then the output should be −

const output = 5;

because the desired longest substring is 'kdkdd'

Example

Following is the code −

const str = 'kdkddj';
const num = 2;
const longestSubstring = (str = '', num) => {
   if(str.length < num){
      return 0
   };
   const map = {}
   for(let char of str) {
      if(char in map){
         map[char] += 1;
      }else{
         map[char] = 1;
      }
   }
   const minChar = Object.keys(map).reduce((minKey, key) => map[key] <
   map[minKey] ? key : minKey)
   if(map[minChar] >= num){
      return str.length;
   };
   substrings = str.split(minChar).filter((subs) => subs.length >= num);
   if(substrings.length == 0){
      return 0;
   };
   let max = 0;
   for(ss of substrings) {
      max = Math.max(max, longestSubstring(ss, num))
   };
   return max;
};
console.log(longestSubstring(str, num));

Output

Following is the console output −

5
raja
Published on 19-Jan-2021 10:35:56
Advertisements