xxxxxxxxxx
def longestSuccessiveElements(a):
n = len(a)
if n == 0:
return 0
# sort the array
a.sort()
lastSmaller = float('-inf')
cnt = 0
longest = 1
# find longest sequence
for i in range(n):
if a[i] - 1 == lastSmaller:
# a[i] is the next element of the
# current sequence
cnt += 1
lastSmaller = a[i]
elif a[i] != lastSmaller:
cnt = 1
lastSmaller = a[i]
longest = max(longest, cnt)
return longest
a = [100, 200, 1, 2, 3, 4]
ans = longestSuccessiveElements(a)
print("The longest consecutive sequence is", ans)
xxxxxxxxxx
/*
Given an array of integers nums, return the length of the longest consecutive
sequence of elements.
A consecutive sequence is a sequence of elements in which each element is
exactly 1 greater than the previous element.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [2,20,4,10,3,4,5]
Output: 4
Explanation: The longest consecutive sequence is [2, 3, 4, 5].
Example 2:
Input: nums = [0,3,2,5,4,6,1,1]
Output: 7
*/
const longestConsecutive = nums => {
let [result, sortedNums, counter, finalLength] = [
[],
nums.sort((a, b) => a - b),
0,
0,
];
for (let i = 0; i < sortedNums.length; i++) {
if (i === 0) result.push(sortedNums[i]);
else {
const subtract = sortedNums[i] - sortedNums[i - 1];
if (subtract === 1) result.push(sortedNums[i]);
else if (subtract === 0) continue;
else {
counter++;
if (counter > 0) {
result = [sortedNums[0]];
counter = 0;
}
}
}
result.length > finalLength ? (finalLength = result.length) : null;
}
return finalLength;
}
const nums = [9,1,-3,2,4,8,3,-1,6,-2,-4,7]
longestConsecutive(nums) // 4
// With love @kouqhar