From 2d96581aabdd1aef3b38555c2288b89dbe1f1d6d Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 12 Jan 2026 04:06:25 -0600 Subject: [PATCH] adding algo --- .../ex_45_longest_consecutive_sequence.py | 28 +++++++++++++++++++ ...5_longest_consecutive_sequence_round_22.py | 23 +++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_22/ex_45_longest_consecutive_sequence.py create mode 100644 tests/test_150_questions_round_22/test_45_longest_consecutive_sequence_round_22.py diff --git a/src/my_project/interviews/top_150_questions_round_22/ex_45_longest_consecutive_sequence.py b/src/my_project/interviews/top_150_questions_round_22/ex_45_longest_consecutive_sequence.py new file mode 100644 index 00000000..8e17164d --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_22/ex_45_longest_consecutive_sequence.py @@ -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 + \ No newline at end of file diff --git a/tests/test_150_questions_round_22/test_45_longest_consecutive_sequence_round_22.py b/tests/test_150_questions_round_22/test_45_longest_consecutive_sequence_round_22.py new file mode 100644 index 00000000..50233e4b --- /dev/null +++ b/tests/test_150_questions_round_22/test_45_longest_consecutive_sequence_round_22.py @@ -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) \ No newline at end of file