Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding longest consecutive joins in JavaScript
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.
Problem Example
For example, if the input to the function is:
const arr = [ [1, 2], [2, 3], [3, 4] ];
Expected Output: 2
Explanation: The longest chain is [1,2] ? [3,4] because 2 < 3, so these pairs can be chained together.
Algorithm Approach
The key insight is to use a greedy approach:
- Sort pairs by their ending values (second element)
- Select pairs that don't overlap with the previously selected pair
- This ensures we get the maximum number of non-overlapping pairs
Solution
const arr = [
[1, 2], [2, 3], [3, 4]
];
const findLongestChain = (arr = []) => {
// Sort by ending values (second element of each pair)
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));
2
Step-by-Step Breakdown
Let's trace through the algorithm with a more complex example:
const arr2 = [[1, 2], [7, 8], [4, 5], [3, 4], [8, 9]];
const findLongestChain = (arr = []) => {
console.log("Original array:", arr);
// Sort by ending values
arr.sort(([, b], [, d]) => b - d);
console.log("Sorted by end values:", arr);
let currentEnd = arr[0][1];
let count = 1;
let chain = [arr[0]];
for (let i = 1; i < arr.length; i++) {
const [start, end] = arr[i];
if (start > currentEnd) {
count += 1;
currentEnd = end;
chain.push([start, end]);
console.log(`Added pair [${start}, ${end}], count: ${count}`);
}
}
console.log("Final chain:", chain);
return count;
}
console.log("Longest chain length:", findLongestChain(arr2));
Original array: [ [ 1, 2 ], [ 7, 8 ], [ 4, 5 ], [ 3, 4 ], [ 8, 9 ] ] Sorted by end values: [ [ 1, 2 ], [ 3, 4 ], [ 4, 5 ], [ 7, 8 ], [ 8, 9 ] ] Added pair [3, 4], count: 2 Added pair [7, 8], count: 3 Final chain: [ [ 1, 2 ], [ 3, 4 ], [ 7, 8 ] ] Longest chain length: 3
How It Works
The algorithm uses a greedy strategy:
- Sort by end values: This ensures we always consider pairs that finish earliest first
- Select non-overlapping pairs: A pair [a, b] can be followed by [c, d] only if b < c
- Maximize count: By choosing pairs that end earliest, we leave maximum room for future pairs
Alternative Example
const testCases = [
[[1, 2], [2, 3], [3, 4]], // Expected: 2
[[1, 2], [7, 8], [4, 5]], // Expected: 3
[[1, 10], [2, 3], [4, 5]], // Expected: 2
];
const findLongestChain = (arr = []) => {
if (arr.length === 0) return 0;
arr.sort(([, b], [, d]) => b - d);
let currentEnd = arr[0][1];
let count = 1;
for (let i = 1; i < arr.length; i++) {
if (arr[i][0] > currentEnd) {
count++;
currentEnd = arr[i][1];
}
}
return count;
}
testCases.forEach((test, index) => {
console.log(`Test ${index + 1}: ${JSON.stringify(test)} ? ${findLongestChain(test)}`);
});
Test 1: [[1,2],[2,3],[3,4]] ? 2 Test 2: [[1,2],[7,8],[4,5]] ? 3 Test 3: [[1,10],[2,3],[4,5]] ? 2
Conclusion
The longest consecutive chain problem is solved efficiently using a greedy algorithm with O(n log n) time complexity. Sort pairs by their ending values and greedily select non-overlapping pairs to maximize the chain length.
