From cb5e32d56d32a830b86088b657964c2f54873cc4 Mon Sep 17 00:00:00 2001 From: Sangeeth Sudheer Date: Tue, 5 Apr 2022 04:07:51 +0530 Subject: [PATCH] feat(0128_longest-consecutive-sequence): add py3 solution --- 0128_longest-consecutive-sequence/README.md | 21 ++++++++++++++++ .../python3/nlogn.py | 24 +++++++++++++++++++ .../python3/solution.py | 0 3 files changed, 45 insertions(+) create mode 100644 0128_longest-consecutive-sequence/README.md create mode 100644 0128_longest-consecutive-sequence/python3/nlogn.py create mode 100644 0128_longest-consecutive-sequence/python3/solution.py diff --git a/0128_longest-consecutive-sequence/README.md b/0128_longest-consecutive-sequence/README.md new file mode 100644 index 0000000..ff35c10 --- /dev/null +++ b/0128_longest-consecutive-sequence/README.md @@ -0,0 +1,21 @@ +Given an unsorted array of integers `nums`, return _the length of the longest consecutive elements sequence._ + +You must write an algorithm that runs in `O(n)` time. + +**Example 1:** + + Input: nums = [100,4,200,1,3,2] + Output: 4 + Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. + + +**Example 2:** + + Input: nums = [0,3,7,2,5,8,4,6,0,1] + Output: 9 + + +**Constraints:** + +* `0 <= nums.length <= 105` +* `-109 <= nums[i] <= 109` \ No newline at end of file diff --git a/0128_longest-consecutive-sequence/python3/nlogn.py b/0128_longest-consecutive-sequence/python3/nlogn.py new file mode 100644 index 0000000..dc9f91a --- /dev/null +++ b/0128_longest-consecutive-sequence/python3/nlogn.py @@ -0,0 +1,24 @@ +# Time: O(NlogN) +# Space: O(1) +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + nums.sort() + + max_length = 1 + l = 1 + + # We don't want to go OOB + for i in range(0, len(nums) - 1): + diff = nums[i + 1] - nums[i] + + # All good, still consecutive. + if diff == 1: + l += 1 + max_length = max(max_length, l) + # We skip to next iteration of loop if + # item repeats. Otherwise, we reset + # running length variable to 1 + elif diff != 0: + l = 1 + + return max_length if len(nums) > 0 else 0 diff --git a/0128_longest-consecutive-sequence/python3/solution.py b/0128_longest-consecutive-sequence/python3/solution.py new file mode 100644 index 0000000..e69de29