Longest Consecutive Sequence in an Array in Python

 

Python Program


def longest_consecutive(nums):
    """
    Find the length of the longest consecutive elements sequence in an array.

    Args:
    nums (List[int]): A list of integers.

    Returns:
    int: The length of the longest consecutive elements sequence.
    """
    if not nums:
        return 0

    # Convert the list to a set for O(1) lookups
    num_set = set(nums)
    longest_streak = 0

    for num in num_set:
        # Only check for streaks starting with the first number
        if num - 1 not in num_set:
            current_num = num
            current_streak = 1

            # Count streak
            while current_num + 1 in num_set:
                current_num += 1
                current_streak += 1

            longest_streak = max(longest_streak, current_streak)

    return longest_streak

# Example usage
if __name__ == "__main__":
    example_array = [100, 4, 200, 1, 3, 2]
    print("Length of longest consecutive sequence:", longest_consecutive(example_array))

Program Structure

The program consists of a function longest_consecutive(nums) which takes a list of integers as input and returns the length of the longest consecutive elements sequence.

Key Components:

  • Input Handling:The function checks if the input list is empty and returns 0 if it is.
  • Using a Set:The input list is converted to a set to allow for O(1) average-time complexity for lookups, which improves performance compared to searching in a list.
  • Finding Consecutive Sequences:For each number in the set, the program checks if it is the start of a consecutive sequence (i.e., the previous number is not in the set). If so, it counts the length of the sequence.
  • Tracking the Longest Streak:The maximum length of consecutive sequences found is stored in longest_streak, which is updated throughout the iterations.

Example Usage

The program includes an example usage section that demonstrates how to call the longest_consecutive function and print the result.

 

Leave a Reply

Your email address will not be published. Required fields are marked *