How to useBrute Force in Javascript
- 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); |
Output
4
Time Complexity: O(N^3)
Space Complexity: O(1)
JavaScript Program to find the Longest Consecutive Sequence of Numbers in an Array
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