Skip to content

Commit b0420d7

Browse files
committed
LeetCode-128: Longest Consecutive Sequence
1 parent 50e054a commit b0420d7

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def longestConsecutive(self, nums: List[int]) -> int:
6+
num_set = set(nums)
7+
longest = 0
8+
9+
for num in num_set:
10+
if (num - 1) not in num_set:
11+
current = 0
12+
while (num + current) in num_set:
13+
current += 1
14+
longest = max(longest, current)
15+
16+
return longest

tests/test_leetcode_medium.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,31 @@ def test_three_sum_closest(nums, target, expected):
174174
assert result == expected, f"expected: {expected} but got: {result}"
175175

176176

177+
@pytest.mark.parametrize(
178+
"nums, expected",
179+
[
180+
([100, 4, 200, 1, 3, 2], 4),
181+
([0, 3, 7, 2, 5, 8, 4, 6, 0, 1], 9),
182+
([1], 1),
183+
([], 0),
184+
([1, 2, 3, 4, 5], 5),
185+
([5, 4, 3, 2, 1], 5),
186+
([1, 1, 1, 1], 1),
187+
([1, 2, 0, 1], 3),
188+
([-1, 0, 1, 2], 4),
189+
([-2, -1, 0, 1, 2], 5),
190+
([10, 30, 20, 40], 1),
191+
([9, 1, 4, 7, 3, -1, 0, 5, 8, -1, 6], 7),
192+
],
193+
)
194+
def test_longest_consecutive(nums, expected):
195+
from LeetCode.medium.longest_consecutive_128 import Solution
196+
197+
result = Solution().longestConsecutive(nums)
198+
199+
assert result == expected
200+
201+
177202
# 05: Longest Palindromic Substring
178203
# https://leetcode.com/problems/longest-palindromic-substring/?envType=problem-list-v2&envId=hash-table
179204

0 commit comments

Comments
 (0)