- 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 sublist with unique elements in Python

Suppose we have a list of numbers called nums, where all elements are unique. We have to find the length of the longest sublist that contains consecutive elements.

So, if the input is like nums = [3, 6, 7, 5, 4, 9], then the output will be 5, because the sublist is [3, 6, 7, 5, 4] this contains all consecutive elements from 3 to 7.

To solve this, we will follow these steps −

- ret := 0
- for i in range 0 to size of nums - 1, do
- lhs := nums[i]
- rhs := nums[i]
- for j in range i to size of nums - 1, do
- lhs := minimum of lhs and nums[j]
- rhs := maximum of rhs and nums[j]
- if (rhs - lhs) is same as (j - i), then
- ret := maximum of ret and (j - i + 1)

- return ret

## Example

Let us see the following implementation to get better understanding −

def solve(nums): ret = 0 for i in range(len(nums)): lhs = nums[i] rhs = nums[i] for j in range(i, len(nums)): lhs = min(lhs, nums[j]) rhs = max(rhs, nums[j]) if rhs - lhs == j - i: ret = max(ret, j - i + 1) return ret nums = [3, 6, 7, 5, 4, 9] print(solve(nums))

## Input

[3, 6, 7, 5, 4, 9]

## Output

1

- Related Articles
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest sublist with given condition in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest sublist with value range condition in Python
- Program to find length of longest consecutive sequence in Python
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find length of longest sublist whose sum is 0 in Python
- Program to find length of longest contiguously strictly increasing sublist after removal in Python
- Program to pack same consecutive elements into sublist in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Program to find length of longest consecutive path of a binary tree in python
- Program to find longest equivalent sublist after K increments in Python
- Program to find length of longest sublist where difference between min and max smaller than k in Python
- Program to find length of longest path with even sum in Python

Advertisements