Longest string with two distinct 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 number (smaller than the length of string) as the second argument. The function should delete characters from the original string and prepare a new string such that it's the longest string containing at most two distinct characters.

Then at last the function should return the length of that desired string.

For example: If the input string is −

const str = 'kjeljsdl';

Then the output should be −

const output = 4;

because the longest substring with at most 2 distinct characters is 'jljl'

Example

The code for this will be −

 Live Demo

const str = 'kjeljsdl';
const longestSubstring = (str = '') => {
   const { length } = str;
   if (length <= 1){
      return 0;
   };
   const keys = [...new Set(str)];
   const arr = [];
   let max = 0;
   for (let i = 0; i < keys.length - 1; i++) {
      for (let j = i + 1; j < keys.length; j++) {
         arr.push(keys[i] + keys[j]);
      }
   }
   arr.forEach(item => {
      let sub = '';
      for (let i = 0; i < str.length; i++) {
         if (sub[sub.length - 1] === str[i]) {
            sub = '';
            break;
         }
         if (item.includes(str[i])) {
            sub += str[i];
         }
      }
      if (sub && sub.length > max){
         max = sub.length;
      };
   });
   return max;
}
console.log(longestSubstring(str));

Output

And the output in the console will be −

4
raja
Published on 24-Feb-2021 10:21:06
Advertisements