From 1c44b21de42c798229ffeaf076657720b09b0f84 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Tue, 5 Apr 2022 05:28:58 +0530 Subject: [PATCH] better soln --- .../python3/solution.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) 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