Find Longest Consecutive Sequence in Python
Find the length of the longest consecutive elements sequence in an unsorted array using a set for O(n) lookups.
Python code
22 linesdef longest_consecutive_length(nums):
num_set = set(nums)
longest = 0
for num in num_set:
if num - 1 not in num_set:
current = num
current_streak = 1
while current + 1 in num_set:
current += 1
current_streak += 1
longest = max(longest, current_streak)
return longest
if __name__ == "__main__":
test_numbers = [100, 4, 200, 1, 3, 2]
result = longest_consecutive_length(test_numbers)
print(result)
Output
4
How it works
The code converts the input list into a set, which gives O(1) average-time membership checks. For each number that is the start of a sequence (no num - 1 in the set), it walks forward counting consecutive numbers in a while loop. Each number is only processed once, so the total time complexity is O(n). The longest variable tracks the maximum streak found across all starting positions.
Common mistakes
- Forgetting to use a set and doing O(n) list membership checks inside the loop
- Starting the while loop for every number instead of only sequence heads
- Modifying the set while iterating over it
Variations
- Use a sorted array and check adjacent differences for O(n log n) complexity
- Use a hash map to track sequence lengths for each endpoint
Real-world use cases
- Finding the longest streak of consecutive logins or activity days per user in analytics pipelines.
- Identifying the largest contiguous block of available IP addresses in network management tools.
- Detecting the longest run of consecutive records in time-series data when checking for gaps or clusters.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.