
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 consecutive sequence in Python
A Consecutive sequence is a series of numbers where each number follows the previous one without any missing the order like 1, 2, 3, 4. It is a set of numbers where each number appears in increasing order by 1, even if not adjacent. We can find the Consecutive sequences in data structures of Python such as lists, strings, tuple, etc.
Using set() function
set() is the built-in function in Python which is used to create a Set data structure. This function is used to eliminate the duplicates from the given input.
We can use set() function to find the longest consecutive sequence, first we have to convert the list into a set to remove duplicates and then for each element, we need to check if it is the beginning of a sequence i.e., num - 1 is not in the set. If it is the start then we will keep incrementing to check for consecutive numbers and update the maximum length accordingly.
Example-1
Following is the example which shows how to use set() function to determine the length of the longest consecutive sequence -
def longest_consecutive_sequence(nums): num_set = set(nums) longest_streak = 0 for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak # Sample input list numbers = [100, 4, 200, 1, 3, 2] print("Length of the longest consecutive sequence:", longest_consecutive_sequence(numbers))
Here is the output of the above example -
Length of the longest consecutive sequence: 4
Example-2
Below is another example where we find the length of the longest consecutive sequence for a string input -
class Solution(object): def longestConsecutive(self, s): # Convert space-separated string to list of integers a = list(map(int, s.strip().split())) a = set(a) longest = 0 for i in a: if i - 1 not in a: current = i streak = 0 while current in a: current += 1 streak += 1 longest = max(longest, streak) return longest ob = Solution() print(ob.longestConsecutive("1 2 3 4 100"))
Below is the output of the above example -
Length of the longest consecutive sequence: 4