- 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

# Program to find length of longest consecutive sequence in Python

Suppose we have an unsorted array of numbers, we have to find the length of the longest sequence of consecutive elements.

So, if the input is like nums = [70, 7, 50, 4, 6, 5], then the output will be 4, as the longest sequence of consecutive elements is [4, 5, 6, 7]. so we return its length: 4.

To solve this, we will follow these steps −

nums := all unique elements of nums

max_cnt := 0

for each num in nums, do

if num - 1 not in nums, then

cnt := 0

while num is present in nums, do

num := num + 1

cnt := cnt + 1

max_cnt := maximum of max_cnt and cnt

return max_cnt

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, nums): nums = set(nums) max_cnt = 0 for num in nums: if num - 1 not in nums: cnt = 0 while num in nums: num += 1 cnt += 1 max_cnt = max(max_cnt, cnt) return max_cnt ob = Solution() nums = [70, 7, 50, 4, 6, 5] print(ob.solve(nums))

## Input

[70, 7, 50, 4, 6, 5]

## Output

4

- Related Articles
- Longest Consecutive Sequence in Python
- 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
- Program to find length of longest consecutive path of a binary tree in python
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Program to find length of longest matrix path length in Python
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic substring in Python
- Program to find length of longest possible stick in Python?
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest fibonacci subsequence in Python
- Binary Tree Longest Consecutive Sequence in C++

Advertisements