Leetcode 128: Longest Consecutive Sequence

grid47
grid47
Exploring patterns and algorithms
Oct 25, 2024 5 min read

A smooth, radiant path showing consecutive numbers, glowing brighter as the sequence length increases.
Solution to LeetCode 128: Longest Consecutive Sequence Problem

Given an unsorted array of integers, return the length of the longest consecutive elements sequence.
Problem
Approach
Steps
Complexity
Input: The input is an unsorted array of integers.
Example: [1, 2, 4, 5, 6, 3]
Constraints:
• 0 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
Output: The output should be the length of the longest consecutive sequence in the array.
Example: 6
Constraints:
• The output will be an integer representing the length of the longest consecutive sequence.
Goal: To find the longest consecutive sequence, we need to track elements and determine the sequence length efficiently.
Steps:
• 1. Insert all elements into a set for constant time lookup.
• 2. For each element, check if it is the start of a new sequence by checking if the previous element (element - 1) is not in the set.
• 3. If it is the start of a sequence, continue checking for consecutive elements by incrementing the current element and counting the sequence length.
• 4. Track the maximum sequence length found.
Goal: The input array will always be valid as per the given constraints.
Steps:
• 0 <= nums.length <= 10^5
• -10^9 <= nums[i] <= 10^9
Assumptions:
• The input array may contain duplicate values which should not affect the length of the longest sequence.
Input: [1, 2, 4, 5, 6, 3]
Explanation: The sequence [1, 2, 3, 4, 5, 6] is the longest consecutive sequence in this array, having length 6.

Input: [10, 100, 5, 11, 6, 7]
Explanation: The longest consecutive sequence is [5, 6, 7, 10, 11] with length 5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus