Medium
Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9
Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109
To solve the "Longest Consecutive Sequence" problem in Python with a Solution class, we'll use a HashSet and a greedy approach. Below are the steps:
-
Create a
Solutionclass: Define a class namedSolutionto encapsulate our solution methods. -
Create a
longestConsecutivemethod: This method takes an arraynumsas input and returns the length of the longest consecutive elements sequence. -
Initialize a HashSet: Create a HashSet named
numSetto store all the numbers in the arraynums. -
Iterate through the array: Add all the numbers from the array
numsto thenumSet. -
Find the longest sequence: Iterate through the array
numsagain. For each numbernumin the array:- Check if
num - 1exists in thenumSet. If it does not,numcould be the start of a new sequence. - If
num - 1does not exist, start a new sequence fromnum. IncrementcurrentNumby 1 and check ifcurrentNumexists in thenumSet. Keep incrementingcurrentNumuntil it does not exist in thenumSet. Update the maximum length of the sequence accordingly.
- Check if
-
Return the maximum length: After iterating through the entire array, return the maximum length of the consecutive sequence.
Here's the Python implementation:
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
max_length = 0
for num in num_set:
if num - 1 not in num_set:
cur_num = num
cur_length = 1
while cur_num + 1 in num_set:
cur_num += 1
cur_length += 1
max_length = max(max_length, cur_length)
return max_lengthThis implementation follows the steps outlined above and efficiently calculates the length of the longest consecutive elements sequence in Python.