- 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 distinct sublist in Python

Suppose we have a list of numbers called nums, and we have to find the length of the longest contiguous sublist where all its elements are unique.

So, if the input is like nums = [6, 2, 4, 6, 3, 4, 5, 2], then the output will be 5, as the longest list of unique elements is [6, 3, 4, 5, 2].

To solve this, we will follow these steps −

head := 0, dct := a new map

max_dist := 0

for each index i and element num in nums, do

if num is in dct and dct[num] >= head, then

head := dct[num] + 1

dct[num] := i

if i - head + 1 > max_dist, then

max_dist := i - head + 1

return max_dist

Let us see the following implementation to get better understanding −

## Example

class Solution: def solve(self, nums): head = 0 dct = {} max_dist = 0 for i, num in enumerate(nums): if num in dct and dct[num] >= head: head = dct[num] + 1 dct[num] = i if i - head + 1 > max_dist: max_dist = i - head + 1 return max_dist ob = Solution() nums = [6, 2, 4, 6, 3, 4, 5, 2] print(ob.solve(nums))

## Input

[6, 2, 4, 6, 3, 4, 5, 2]

## Output

5

- 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 sublist whose sum is 0 in Python
- Program to find length of longest strictly increasing then decreasing sublist in Python
- Program to find length of longest consecutive sublist with unique elements in Python
- Program to find length of longest sublist with value range condition in Python
- Program to find length of longest contiguously strictly increasing sublist after removal in Python
- Program to find length of longest contiguous sublist with same first letter words in Python
- Program to find length of longest sublist containing repeated numbers by k operations in Python
- Program to find length of longest substring which contains k distinct characters in Python
- Program to find the length of longest substring which has two distinct elements 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 contiguous strictly increasing sublist in Python
- Program to find length of longest matrix path length in Python

Advertisements