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.

Medium Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

22 lines
Python 3.9+
def 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

stdout
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

  1. Use a sorted array and check adjacent differences for O(n log n) complexity
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.