JavaScript Program to find the Longest Consecutive Sequence of Numbers in an Array
Last Updated :
15 Sep, 2023
In this article, we are going to find the longest consecutive sequence of numbers in an array using JavaScript language. We are given an array that consists of integers we need to find the longest subsequence such that elements in the subsequence are consecutive integers, these numbers are in any order.
Example:
Input: inputArray[] = [1, 9, 3, 10, 4, 20, 2]
Output: 4
Explanation: The subsequence 1, 3, 4, 2 is the longest subsequence of consecutive elements
Approaches to Find the Longest Consecutive Sequence of Numbers in an Array in JavaScript
- Using JavaScript Set
- Using Sorting in JavaScript
- Using Brute Force
So, let's see each of the approaches with its implementation.
- In this approach, we use the JS Set that finds the longest consecutive subsequence. We take the array as the input and check if the array is empty, if it is not empty then we create the set of all elements in the input array.
- Then we iterate through the input array. For each element, we are checking the predecessor is in the set, if it is not, then we are starting a new consecutive subsequence with that element.
- We are keeping track of the length of the longest consecutive subsequence and printing it at the end.
Example: In this example, we will find the longest consecutive sequence of numbers in an array using Set in JavaScript.
JavaScript
function longConsequtiveSeqUsingSet(inputarry) {
if (inputarry == null || inputarry.length === 0) {
return 0;
}
let set = new Set(inputarry);
let outputLongValue = 0;
for (let temp of inputarry) {
if (!set.has(temp - 1)) {
let count = 0;
while (set.has(count + temp)) {
count++;
}
outputLongValue = Math.max(
outputLongValue,
count
);
}
}
return outputLongValue;
}
let inputArray = [36, 41, 56, 35, 44, 33, 34, 92, 43, 32, 42];
console.log(longConsequtiveSeqUsingSet(inputArray));
Time compexity: O(n)
Space compleity: O(n)
- In this apporach, we are using the Sorting apporach, were firstly we are checking whteger the array is empty, of not, then we are sorting the array in the asecending order.
- After that, we are going thorugh all thw alements of the array by maintinag the count of the consequtib element.
- The longest subsequence is the maxium count whilch will be printed at the end.
Example: In this example, we will find the longest consecutive sequence of numbers in an array using Sorting technique in JavaScript.
JavaScript
function longConsequtiveSeqUsingSorting(inputarray) {
if (inputarray.length === 0) {
return 0;
}
inputarray.sort((a, b) => a - b);
let countValue = 1;
let maxcountValue = 1;
for (let i = 1; i < inputarray.length; i++) {
if (inputarray[i - 1] + 1 === inputarray[i]) {
countValue++;
} else if (inputarray[i - 1] !== inputarray[i]) {
countValue = 1;
}
maxcountValue = Math.max(maxcountValue, countValue);
}
return maxcountValue;
}
const inputArray = [1, 9, 3, 10, 4, 20, 2];
const outputLongValue =
longConsequtiveSeqUsingSorting(inputArray);
console.log(outputLongValue);
Time Complexity: O(N * log(N))
Space Complexity: O(1)
Approach 3: Using Brute Force
- In this approach, we are starightforwardly using the Brute Force in JavaScript, where we are starting from the each element of the input array and checking whrther it is the start of tje lomgest consecutive subsequence.
- We are doing this by starting from the lement and adding all the consecutive elements to the subsequence till we are not reaching an element tht is not consecutive toots provious element.
- We are tacking the longest consecutive subsequence and printing it.
Example: In this example, we will find the longest consecutive sequence of numbers in an array using Brute Force method in JavaScript.
JavaScript
function longConsequtiveSeqUsingBrute(inputArray) {
let longestLength = 0;
for (let i = 0; i < inputArray.length; i++) {
let currentNumValue = inputArray[i];
let currentLengthValue = 1;
while (inputArray.includes(currentNumValue + 1)) {
currentNumValue += 1;
currentLengthValue += 1;
}
if (currentLengthValue > longestLength) {
longestLength = currentLengthValue;
}
}
return longestLength;
}
const inputArray = [1, 9, 3, 10, 4, 20, 2];
const outputLongValue =
longConsequtiveSeqUsingBrute(inputArray);
console.log(outputLongValue);
Time Complexity: O(N^3)
Space Complexity: O(1)
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read