
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Longest Consecutive Sequence in Python
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
Example
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]))
Input
[100,4,250,1,3,2]
Output
4
- Related Articles
- Program to find length of longest consecutive sequence in Python
- Binary Tree Longest Consecutive Sequence in C++
- Binary Tree Longest Consecutive Sequence II in C++
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Find longest consecutive letter and digit substring in Python
- Longest Arithmetic Sequence in C++
- How to find longest repetitive sequence in a string in Python?
- Finding longest consecutive joins in JavaScript
- Finding the longest "uncommon" sequence in JavaScript
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find length longest prefix sequence of a word array in Python
- Can array form consecutive sequence - JavaScript
- Longest Line of Consecutive One in Matrix in C++
- Program to find length of longest consecutive path of a binary tree in python
- Program to find longest consecutive run of 1s in binary form of n in Python

Advertisements