Skip to content

Commit ffdbc64

Browse files
authored
Merge pull request #1514 from ivan1016017/january12
adding algo
2 parents 939f87e + 2d96581 commit ffdbc64

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def longestConsecutive(self, nums: List[int]) -> int:
6+
if not nums:
7+
return 0
8+
9+
# Convert to set for O(1) lookup
10+
num_set = set(nums)
11+
max_length = 0
12+
13+
for num in num_set:
14+
# Only start counting if this is the beginning of a sequence
15+
# (i.e., num - 1 is not in the set)
16+
if num - 1 not in num_set:
17+
current_num = num
18+
current_length = 1
19+
20+
# Count consecutive numbers
21+
while current_num + 1 in num_set:
22+
current_num += 1
23+
current_length += 1
24+
25+
max_length = max(max_length, current_length)
26+
27+
return max_length
28+
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_45_longest_consecutive_sequence import Solution
4+
5+
class LongestConsecutiveSequenceTestCase(unittest.TestCase):
6+
7+
def test_first_pattern(self):
8+
solution = Solution()
9+
output = solution.longestConsecutive(nums = [100,4,200,1,3,2])
10+
target = 4
11+
self.assertEqual(output, target)
12+
13+
def test_second_pattern(self):
14+
solution = Solution()
15+
output = solution.longestConsecutive(nums = [0,3,7,2,5,8,4,6,0,1])
16+
target = 9
17+
self.assertEqual(output, target)
18+
19+
def test_third_pattern(self):
20+
solution = Solution()
21+
output = solution.longestConsecutive(nums = [1,0,1,2])
22+
target = 3
23+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)