mirror of
https://github.com/Rainyy21/framework_note.git
synced 2026-10-10 22:50:29 -04:00
2.7 KiB
2.7 KiB
id, title, difficulty, tags, status, date_solved, leetcode_url, review_needed
| id | title | difficulty | tags | status | date_solved | leetcode_url | review_needed | |||
|---|---|---|---|---|---|---|---|---|---|---|
| 128 | Longest Consecutive Sequence | Medium |
|
Solved | 2026-06-05 | https://leetcode.com/problems/longest-consecutive-sequence/ | false |
128. Longest Consecutive Sequence
[!info] Problem Link: LeetCode - Longest Consecutive Sequence
📝 Problem Description
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:4Explanation: 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
💡 Approaches & Explanations
Approach 1: Hash Set — Optimal
To achieve O(n) time complexity, we use a hash set for O(1) lookups. The core idea is to identify the start of each possible sequence. A number n is the start of a sequence if n - 1 is not present in the set.
- Insert all numbers from
numsinto a hash set. - Iterate through each number
nin the set:- Check if
n - 1is in the set. - If
n - 1is NOT in the set,nis the start of a sequence. - From
n, keep checking forn + 1,n + 2, ... and increment the current sequence length. - Update the maximum length found so far.
- Check if
📊 Complexity Analysis
- Time Complexity:
O(N)whereNis the number of elements. Although there is a nested while loop, each element is visited at most twice (once by the main loop and once by the while loop), resulting in linear time. - Space Complexity:
O(N)to store the elements in the hash set.
💻 Code Implementations
Python3
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
longest = 0
for n in num_set:
# Check if n is the start of a sequence
if (n - 1) not in num_set:
length = 1
while (n + length) in num_set:
length += 1
longest = max(length, longest)
return longest
🧠 Key Takeaways & Lessons
- Identifying Sequence Starts: By checking for the absence of
n - 1, we ensure that we only start counting from the beginning of a sequence, avoiding redundant work. - Hash Set for Efficiency: Trading space for time by using a Hash Set allows us to reduce what would be an
O(n^2)orO(n \log n)problem intoO(n).