Finding longest consecutive joins in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of pairs of numbers, arr, as the first and the only argument. In every pair, the first number is always smaller than the second number.

Now, we define a pair (c, d) that can follow another pair (a, b) if and only if b < c. Chain of pairs can be formed in this fashion. Our function is supposed to find the length longest chain which can be formed.

For example, if the input to the function is

Input

const arr = [
   [1, 2], [2, 3], [3, 4]
];

Output

const output = 2;

Output Explanation

The longest chain is [1,2] -> [3,4]

Example

   Following is the code −

 Live Demo

const arr = [
[1, 2], [2, 3], [3, 4]
];
const findLongestChain = (arr = []) => {
   arr.sort(([, b], [, d]) => b - d)
   let currentEnd = arr[0][1]
   let count = 1
   for (const [start, end] of arr) {
      if (start > currentEnd) {
         count += 1
         currentEnd = end
      }
   }
   return count
}
console.log(findLongestChain(arr));

Output

2
raja
Published on 24-Apr-2021 10:33:18
Advertisements