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 −
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