- Related Questions & Answers
- Binary Tree Longest Consecutive Sequence in C++
- Program to find length of longest consecutive sequence in Python
- Binary Tree Longest Consecutive Sequence II in C++
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Longest Arithmetic Sequence in C++
- Find longest consecutive letter and digit substring in Python
- Finding longest consecutive joins in JavaScript
- Can array form consecutive sequence - JavaScript
- How to find longest repetitive sequence in a string in Python?
- Longest Line of Consecutive One in Matrix in C++
- Longest consecutive path from a given starting character
- Longest string consisting of n consecutive strings in JavaScript
- Finding the longest "uncommon" sequence in JavaScript
- Program to find length of longest consecutive path of a binary tree in python
- Finding the longest non-negative sum sequence using JavaScript

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have an array of integers. We have to find the length of the longest consecutive elements sequence. So if the input is like [100, 4, 250, 1, 3, 2], answer will be 4, as the longest consecutive sequence is [1,2,3,4].

To solve this, we will follow these steps −

make the array set, longest := 0

for i in range array −

if i – 1 is not in a −

current := i, streak := 0

while i in a −

increase i by 1, increase streak by 1

longest := max of longest and streak

return longest

Let us see the following implementation to get a better understanding −

class Solution(object): def longestConsecutive(self, a): a = set(a) longest = 0 for i in a: if i-1 not in a: current = i streak = 0 while i in a: i+=1 streak+=1 longest = max(longest,streak) return longest ob = Solution() print(ob.longestConsecutive([100,4,250,1,3,2]))

[100,4,250,1,3,2]

4

Advertisements