Finding the longest substring uncommon in array in JavaScript

JavascriptWeb DevelopmentFront End Technology

Subsequence

For the purpose of this problem, we define a subsequence as a sequence that can be derived from one sequence by deleting some characters without changing the order of the remaining elements. Any string is a subsequence of itself and an empty string is a subsequence of any string.

Problem

We are required to write a JavaScript function that takes in an array of strings as the only argument. Our function needs to find the length of the longest uncommon subsequence among them.

By longest uncommon subsequence we mean, longest subsequence of one of the strings in the array and this subsequence should not be any subsequence of the other strings in the array.

If there exists no uncommon subsequence, we should return -1.

For example, if the input to the function is −

const arr = ["aba", "cdc", "eae"];

Then the output should be −

const output = 3;

Output Explanation:

“aba”, “cdc” and “eae” are all valid uncommon subsequence of length 3.

Example

The code for this will be −

 Live Demo

const arr = ["aba", "cdc", "eae"];
const longestUncommon = (strs) => {
   const map = {};
   const arr = [];
   let max = -1;
   let index = -1;
   for(let i = 0; i < strs.length; i++){
      map[strs[i]] = (map[strs[i]] || 0) + 1;
      if(map[strs[i]] > 1){
         if(max < strs[i].length){
            max = strs[i].length
            index = i;
         }
      }
   }
   if(index === -1) {
      strs.forEach(el =>{
         if(el.length > max) max = el.length;
      })
      return max;
   }
   for(let i = 0; i < strs.length; i++){
      if(map[strs[i]] === 1) arr.push(strs[i]);
   }
   max = -1
   for(let i = arr.length - 1; i >= 0; i--){
      let l = arr[i];
      let d = 0;
      for(let j = 0; j < strs[index].length; j++){
         if(strs[index][j] === l[d]){
            d++;
         }
      }
      if(d === l.length){
         let temp = arr[i];
         arr[i] = arr[arr.length - 1];
         arr[arr.length - 1] = temp;
         arr.pop();
      }
   }
   arr.forEach(el =>{
      if(el.length > max) max = el.length;
   })
   return max;
};
console.log(longestUncommon(arr));

Output

And the output in the console will be −

3
raja
Published on 03-Mar-2021 06:04:28
Advertisements