Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 distinct sublist in Python
A distinct sublist is a continuous portion of a list in which all the elements are different from each other. The goal is to find the maximum length of such a sublist within a given list of elements.
In Python, a list is an ordered and mutable data structure in which sequence of elements are enclosed in square brackets []. The elements in a list can be of any datatype such as integer, float, string etc., and each element in a list has a unique index position which starts from 0.
Using set() function
The set() is a built-in function in Python which is used create a set data structure to store unique elements. To find the longest sublist with all unique elements, we can use a sliding window approach. In this approach, we maintain a set to track elements in the current window. If a duplicate is found then we reduce the window size by moving to the left until the duplicate is removed. The longest distinct sublist is the maximum window size.
Example-1
Following is the example which shows how to use set() function to calculate the length of the longest sublist with unique elements -
def longest_distinct_sublist(lst):
seen = set()
left = 0
max_len = 0
for right in range(len(lst)):
while lst[right] in seen:
seen.remove(lst[left])
left += 1
seen.add(lst[right])
max_len = max(max_len, right - left + 1)
return max_len
# Sample input list
numbers = [1, 2, 3, 2, 4, 5]
print("Length of longest distinct sublist:", longest_distinct_sublist(numbers))
Here is the output of the above example -
Length of longest distinct sublist: 4
Example-2
Below is another example where we calculate the longest distinct sublist which contains only distinct elements using the set() function -
def longest_distinct_sublist(lst):
seen = set()
start = 0
max_length = 0
for end in range(len(lst)):
while lst[end] in seen:
seen.remove(lst[start])
start += 1
seen.add(lst[end])
max_length = max(max_length, end - start + 1)
return max_length
# Sample input list
numbers = [5, 1, 3, 5, 2, 3, 4, 1]
print("Longest distinct sublist length:", longest_distinct_sublist(numbers))
Below is the output of the above example -
Longest distinct sublist length: 5