Finding the longest "uncommon" sequence in JavaScript


We are required to write a JavaScript function that takes in an array of strings. The function should find the longest uncommon subsequence among the strings of the array.

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

Our function should return the length of this longest uncommon subsequence.

For example: If the input array is −

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

Then the output should be 3.

Example

The code for this will be −

const arr = ["aba", "cdc", "eae"];
const findUncommonLength = (array = []) => {
   const seen = {};
   const arr = [];
   let max = −1;
   let index = −1;
   for(let i = 0; i < array.length; i++){
      seen[array[i]] = (seen[array[i]] || 0) + 1;
      if(seen[array[i]] > 1){
         if(max < array[i].length){
            max = array[i].length
            index = i;
         }
      }
   };
   if(index === −1) {
      array.forEach(el =>{
         if(el.length > max) max = el.length;
      })
      return max;
   };
   for(let i = 0; i < array.length; i++){
      if(seen[array[i]] === 1) arr.push(array[i]);
   };
   max = −1;
   for(let i = arr.length − 1; i >= 0; i−−){
      let l = arr[i];
      let d = 0;
      for(let j = 0; j < array[index].length; j++){
         if(array[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(findUncommonLength(arr));

Output

And the output in the console will be −

3

Updated on: 24-Nov-2020

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements