Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 [3, 6, 7, 5, 4] contains all consecutive elements from 3 to 7.
Algorithm Approach
To solve this, we will follow these steps ā
- Initialize
ret := 0to store the maximum length - For each starting position
i, do:- Set
lhs := nums[i]andrhs := nums[i] - For each ending position
jfromionwards:- Update
lhs := minimum of lhs and nums[j] - Update
rhs := maximum of rhs and nums[j] - If
(rhs - lhs) == (j - i), then elements form consecutive sequence - Update
ret := maximum of ret and (j - i + 1)
- Update
- Set
- Return
ret
How It Works
The key insight is that for a sublist to contain consecutive elements, the difference between maximum and minimum values should equal the number of elements minus 1. If we have n consecutive numbers, then max - min = n - 1, which means max - min = (ending_index - starting_index).
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]
result = solve(nums)
print(f"Input: {nums}")
print(f"Length of longest consecutive sublist: {result}")
Input: [3, 6, 7, 5, 4, 9] Length of longest consecutive sublist: 5
Step-by-Step Trace
For the sublist [3, 6, 7, 5, 4] ā
- Minimum value: 3
- Maximum value: 7
- Length: 5
- Check:
7 - 3 = 4and5 - 1 = 4?
Alternative Example
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
# Test with different input
nums = [1, 3, 2, 4, 6, 5]
result = solve(nums)
print(f"Input: {nums}")
print(f"Length of longest consecutive sublist: {result}")
Input: [1, 3, 2, 4, 6, 5] Length of longest consecutive sublist: 6
Conclusion
This algorithm uses a brute force approach with O(n²) time complexity to find the longest consecutive sublist. The key insight is checking if the range of values equals the sublist length, indicating consecutive elements.
