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: 2020-11-24T06:45:16+05:30

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements