Created
March 22, 2023 14:02
-
-
Save anushshukla/d7413bc5479b6a1a20bb02b17672c741 to your computer and use it in GitHub Desktop.
Longest sequence count
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * You are given an unsorted array/list 'ARR' of 'N' integers. | |
| * Your task is to return the length of the longest consecutive sequence. | |
| * The consecutive sequence is in the form ['NUM', 'NUM' + 1, 'NUM' + 2, ..., 'NUM' + L] | |
| * where 'NUM' is the starting integer of the sequence and 'L' + 1 is the length of the sequence. | |
| */ | |
| function getHighestSequence(nums) { | |
| const numIndex = {}; | |
| let highestPatternNumber = 0; | |
| function safeUpdateHashmap(key, value) { | |
| if (key in numIndex) { | |
| numIndex[key] = value; | |
| } | |
| } | |
| for (let num of nums) { | |
| num = parseInt(num); | |
| if (numIndex[num]) { | |
| continue; | |
| } | |
| const nextNum = num + 1; | |
| const prevNum = num - 1; | |
| const nextNumSeqCnt = numIndex[nextNum] || 0; | |
| const prevNumSeqCnt = numIndex[prevNum] || 0; | |
| const sequenceCount = 1 + nextNumSeqCnt + prevNumSeqCnt; | |
| const prevHighestSequence = numIndex[highestPatternNumber] || 0; | |
| const isHighestSequence = sequenceCount > prevHighestSequence; | |
| const tail = prevNumSeqCnt && num - prevNumSeqCnt; | |
| const head = nextNumSeqCnt && num + nextNumSeqCnt; | |
| if (isHighestSequence) { | |
| highestPatternNumber = tail || head || num; | |
| } | |
| safeUpdateHashmap(tail, sequenceCount); | |
| safeUpdateHashmap(head, sequenceCount); | |
| // console.log(JSON.stringify({ num, isHighestSequence, prevHighestSequence, sequenceCount, highestPatternNumber, nextNum, prevNum, nextNumSeqCnt, prevNumSeqCnt, tail, head })); | |
| numIndex[num] = sequenceCount; | |
| } | |
| // console.log(JSON.stringify({ nums, numIndex, highestPatternNumber })); | |
| return numIndex[highestPatternNumber]; | |
| } | |
| const testCases = [ | |
| { input: [0, 0], output: 1 }, | |
| { input: [1, 2, 0, 1], output: 3 }, | |
| { input: [100, 4, 200, 1, 3, 2], output: 4 }, | |
| { input: [100000000], output: 1 }, | |
| { input: [100, 100, 100, 100, 99, 101, 101, 101, 101, 101], output: 3 }, | |
| { input: [2, 2, 2, 1, 9], output: 2 }, | |
| ]; | |
| for (testCase of testCases) { | |
| const { input, output } = testCase; | |
| const actualOutput = getHighestSequence(testCase.input); | |
| console.log({ input, output, actualOutput }); | |
| } | |
| ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment