Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from typing import List, Union, Collection, Mapping, Optional
from abc import ABC, abstractmethod

class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
if not nums:
return 0

# Convert to set for O(1) lookup
num_set = set(nums)
max_length = 0

for num in num_set:
# Only start counting if this is the beginning of a sequence
# (i.e., num - 1 is not in the set)
if num - 1 not in num_set:
current_num = num
current_length = 1

# Count consecutive numbers
while current_num + 1 in num_set:
current_num += 1
current_length += 1

max_length = max(max_length, current_length)

return max_length

Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import unittest
from src.my_project.interviews.top_150_questions_round_22\
.ex_45_longest_consecutive_sequence import Solution

class LongestConsecutiveSequenceTestCase(unittest.TestCase):

def test_first_pattern(self):
solution = Solution()
output = solution.longestConsecutive(nums = [100,4,200,1,3,2])
target = 4
self.assertEqual(output, target)

def test_second_pattern(self):
solution = Solution()
output = solution.longestConsecutive(nums = [0,3,7,2,5,8,4,6,0,1])
target = 9
self.assertEqual(output, target)

def test_third_pattern(self):
solution = Solution()
output = solution.longestConsecutive(nums = [1,0,1,2])
target = 3
self.assertEqual(output, target)