def test(fn):
= 1,100
val1, val2 = 9
expected
= fn(low,high)
actual assert actual == expected
Problem Source: Leetcode
Problem Description
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.
tests
Solution
- Time Complexity:
O(n)
- Space Complexity:
O(n)
from typing import List
def longestConsecutive(nums: List[int]) -> int:
= set(nums)
numset = 0
max_seq_len
for num in nums:
# if beginning of a sequence
if num-1 not in numset:
= num
seq_start = 1
seq_length
# Keep incrementing values until you're at end of sequence
while seq_start + 1 in numset:
+= 1
seq_length += 1
seq_start
# Keep sequence length if it's the longest so far
= max(max_seq_len, seq_length)
max_seq_len return max_seq_len