Skip to content

Commit b18071e

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 128 Longest Consecutive Sequence
1 parent 9d3db91 commit b18071e

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1515
- [121 Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/)
1616
- [122 Best Time to Buy and Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/)
1717
- [125 Valid Palindrome](https://leetcode.com/problems/valid-palindrome/description/)
18+
- [128 Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence/description/)
1819
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1920
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
2021
- [202 Happy Number](https://leetcode.com/problems/happy-number/description/)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def longestConsecutive(self, nums: List[int]) -> int:
6+
"""
7+
Given an unsorted array of integers nums, return the length of the
8+
longest consecutive elements sequence.
9+
10+
You must write an algorithm that runs in O(n) time.
11+
"""
12+
nums = set(nums)
13+
longest = 0
14+
for n in nums:
15+
if n - 1 not in nums:
16+
length = 0
17+
while (n + length) in nums:
18+
length += 1
19+
longest = max(longest, length)
20+
return longest
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import List
2+
import pytest
3+
4+
from awesome_python_leetcode._128_longest_consecutive_sequence import Solution
5+
6+
7+
@pytest.mark.parametrize(
8+
argnames=["nums", "expected"],
9+
argvalues=[
10+
([100, 4, 200, 1, 3, 2], 4),
11+
([0, 3, 7, 2, 5, 8, 4, 6, 0, 1], 9),
12+
([1, 0, 1, 2], 3),
13+
],
14+
)
15+
def test_func(nums: List[int], expected: int):
16+
longest_consecutive = Solution().longestConsecutive(nums)
17+
assert longest_consecutive == expected

0 commit comments

Comments
 (0)