- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding longest consecutive joins in JavaScript
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
- Related Articles
- Finding the longest common consecutive substring between two strings in JavaScript
- Finding the longest consecutive appearance of a character in another string using JavaScript
- Finding the character with longest consecutive repetitions in a string and its length using JavaScript
- Finding the longest "uncommon" sequence in JavaScript
- Finding three desired consecutive numbers in JavaScript
- Finding the longest valid parentheses JavaScript
- Finding clusters of consecutive negative integers in JavaScript
- Longest string consisting of n consecutive strings in JavaScript
- Finding the longest substring uncommon in array in JavaScript
- Finding the longest string in an array in JavaScript
- Finding the longest word in a string in JavaScript
- Finding longest substring between two same characters JavaScript
- Finding longest line of 1s in a matrix in JavaScript
- Longest Consecutive Sequence in Python
- Finding all the longest strings from an array in JavaScript

Advertisements