- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

# 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 Questions & Answers
- Program to find length of longest alternating inequality elements sublist in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest sublist with given condition 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 find length of longest consecutive path of a binary tree in python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Program to pack same consecutive elements into sublist in Python
- Program to find length of longest matrix path length in Python
- Program to find length of substring with consecutive common characters in Python
- Program to find length of contiguous strictly increasing sublist in Python

Advertisements