Longest Consecutive Sequence in Python

The Longest Consecutive Sequence problem asks us to find the length of the longest sequence of consecutive integers in an unsorted array. For example, in the array [100, 4, 250, 1, 3, 2], the longest consecutive sequence is [1, 2, 3, 4] with length 4.

Algorithm Approach

We use a set-based approach for O(n) time complexity ?

  • Convert the array to a set for O(1) lookup operations

  • For each number, check if it's the start of a sequence (i.e., number-1 is not in the set)

  • If it's a sequence start, count consecutive numbers and track the maximum length

Implementation

def longest_consecutive(nums):
    if not nums:
        return 0
    
    num_set = set(nums)
    longest = 0
    
    for num in num_set:
        # Check if this is the start of a sequence
        if num - 1 not in num_set:
            current_num = num
            current_streak = 1
            
            # Count consecutive numbers
            while current_num + 1 in num_set:
                current_num += 1
                current_streak += 1
            
            longest = max(longest, current_streak)
    
    return longest

# Test the function
numbers = [100, 4, 250, 1, 3, 2]
result = longest_consecutive(numbers)
print(f"Input: {numbers}")
print(f"Longest consecutive sequence length: {result}")
Input: [100, 4, 250, 1, 3, 2]
Longest consecutive sequence length: 4

How It Works

Let's trace through the algorithm with our example [100, 4, 250, 1, 3, 2] ?

def longest_consecutive_detailed(nums):
    num_set = set(nums)
    longest = 0
    
    print(f"Set: {sorted(num_set)}")
    
    for num in sorted(num_set):  # Sort for clearer demonstration
        if num - 1 not in num_set:
            print(f"\n{num} is start of sequence (no {num-1})")
            current_num = num
            current_streak = 1
            
            while current_num + 1 in num_set:
                current_num += 1
                current_streak += 1
                print(f"  Found {current_num}, streak = {current_streak}")
            
            longest = max(longest, current_streak)
            print(f"  Sequence length: {current_streak}")
    
    return longest

numbers = [100, 4, 250, 1, 3, 2]
result = longest_consecutive_detailed(numbers)
print(f"\nFinal result: {result}")
Set: [1, 2, 3, 4, 100, 250]

1 is start of sequence (no 0)
  Found 2, streak = 2
  Found 3, streak = 3
  Found 4, streak = 4
  Sequence length: 4

100 is start of sequence (no 99)
  Sequence length: 1

250 is start of sequence (no 249)
  Sequence length: 1

Final result: 4

Time and Space Complexity

Complexity Value Explanation
Time O(n) Each number is visited at most twice
Space O(n) Set storage for all numbers

Edge Cases

# Test edge cases
test_cases = [
    [],                    # Empty array
    [1],                   # Single element
    [1, 1, 1],            # Duplicates
    [1, 3, 5, 7],         # No consecutive numbers
    [5, 4, 3, 2, 1]       # Reverse order consecutive
]

for i, nums in enumerate(test_cases):
    result = longest_consecutive(nums)
    print(f"Test {i+1}: {nums} ? {result}")
Test 1: [] ? 0
Test 2: [1] ? 1
Test 3: [1, 1, 1] ? 1
Test 4: [1, 3, 5, 7] ? 1
Test 5: [5, 4, 3, 2, 1] ? 5

Conclusion

The set-based approach efficiently finds the longest consecutive sequence in O(n) time by identifying sequence starts and counting consecutive elements. This algorithm handles duplicates naturally and works for any order of input numbers.

Updated on: 2026-03-25T08:39:34+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements