Python
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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)