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: 9Constraints:
0 <= nums.length <= 105-109 <= nums[i] <= 109
SOLUTION:
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set: set[int]=set(nums)
longest_Seq: int=0
for i in nums:
#check if preceding element exist
if i-1 not in num_set:
current_seq: int=0
while i+1 in num_set:
current_seq +=1
i+=1
longest_Seq= max(current_seq, longest_Seq)
return longest_Seq
Time Complexity: O(n)
- The code iterates through each element in the
numslist once, resulting in a linear time complexity relative to the size of the input. - The operations performed within the loop, such as checking element existence in the set and incrementing values, have constant time complexity.
- Overall, the time complexity is dominated by the loop iteration, resulting in a linear time complexity of O(n).
Space Complexity: O(n)
- The space complexity is determined by the additional memory used to store the set
num_set. - In the worst case, where all elements in
numsare unique, the setnum_setwould contain all elements ofnums. - Therefore, the space complexity is proportional to the size of the input, resulting in O(n) space complexity.
How it works:
num_set: set[int] = set(nums): Creates a setnum_setcontaining unique elements from the inputnumslist.longest_Seq: int = 0: Initializes the variablelongest_Seqwith the value0, which will store the length of the longest consecutive sequence found.for i in nums:: Iterates over each elementiin thenumslist.if i - 1 not in num_set:: Checks if the preceding element ofidoes not exist in thenum_set. If so, it meansiis the start of a consecutive sequence.current_seq: int = 0: Initializes the variablecurrent_seqwith the value0, which will store the length of the current consecutive sequence.while i + 1 in num_set:: Enters a loop that continues as long as the next consecutive element ofiexists in thenum_set.current_seq += 1: Increments thecurrent_seqby1to track the length of the consecutive sequence.i += 1: Increments the value ofiby1to move to the next consecutive element in the sequence.longest_Seq = max(current_seq, longest_Seq): Updates the value oflongest_Seqwith the maximum value betweencurrent_seqandlongest_Seq, ensuring it holds the length of the longest consecutive sequence encountered so far.return longest_Seq: Returns the value oflongest_Seqas the result of the method.

Comments
Post a Comment