diff --git a/0128_longest-consecutive-sequence/python3/solution.py b/0128_longest-consecutive-sequence/python3/solution.py index e69de29..9b9174b 100644 --- a/0128_longest-consecutive-sequence/python3/solution.py +++ b/0128_longest-consecutive-sequence/python3/solution.py @@ -0,0 +1,32 @@ +# Time: O(N) +# Space: O(N) +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + visited = {} + + for _, num in enumerate(nums): + visited[num] = False + + maxl = 0 + + for _, num in enumerate(nums): + if visited[num]: + continue + + l = 1 + prev = num - 1 + while prev in visited: + visited[prev] = True + l += 1 + prev -= 1 + + next = num + 1 + while next in visited: + visited[next] = True + l += 1 + next += 1 + + maxl = max(maxl, l) + + return maxl + \ No newline at end of file