🎢 ELI5 Park / Arrays & Hashing / Longest Consecutive Sequence
Medium

Longest Consecutive Sequence

👶 The 5-Year-Old Summary

You have scattered number cards on the table. Find the longest chain of numbers that can be connected like 100 → 101 → 102 → 103! How long is your longest chain?

🎮 Interactive Visualizer

Click "Step" to find the longest consecutive chain!

Input: [100, 4, 200, 1, 3, 2]

Set (all numbers):

Current chain being built:

🧠 The Brain Hack

Start with the beginning of each chain! Only start counting if "num-1" doesn't exist. This way we don't redo work. It's like starting a new train from the engine, not the middle cars!

💻 The Clean Solution

def longest_consecutive(nums):
    # Edge case: empty array
    if not nums:
        return 0
    
    # Put all numbers in a set for fast lookup
    num_set = set(nums)
    
    longest = 0
    
    # Check each number
    for num in num_set:
        # Only start counting if this is the START of a chain
        # (i.e., num-1 doesn't exist in our set)
        if num - 1 not in num_set:
            current = num
            streak = 1
            
            # Keep counting up while we find consecutive numbers
            while current + 1 in num_set:
                current += 1
                streak += 1
            
            # Update longest if this streak is bigger
            longest = max(longest, streak)
    
    return longest

# Try it!
nums = [100, 4, 200, 1, 3, 2]
print(longest_consecutive(nums))  # Output: 4
# The sequence is [1, 2, 3, 4]

Time: O(n) - Each number is visited at most twice!

Space: O(n) - For the set of numbers