File tree Expand file tree Collapse file tree 2 files changed +30
-38
lines changed
longest-consecutive-sequence Expand file tree Collapse file tree 2 files changed +30
-38
lines changed Load Diff This file was deleted.
Original file line number Diff line number Diff line change 1+ from typing import List
2+
3+
4+ class Solution :
5+ def longestConsecutive (self , nums : List [int ]) -> int :
6+ # Time Complexity: O(n) where n is the length of nums
7+ # Strategy: Use a set for O(1) lookups and only extend sequences from their starting points
8+ if not nums :
9+ return 0
10+
11+ max_streak = 0
12+ num_set = set (nums )
13+
14+ # Only check sequences from their starting points to avoid redundant work
15+ for num in num_set :
16+ current_streak = 0
17+
18+ # Check if this number is the start of a sequence (no left neighbor)
19+ if num - 1 not in num_set :
20+ # Found a sequence start - extend it as far as possible
21+ current_num = num
22+
23+ while current_num in num_set :
24+ current_streak += 1
25+ current_num += 1
26+
27+ # Update the longest streak found so far
28+ max_streak = max (max_streak , current_streak )
29+
30+ return max_streak
You can’t perform that action at this time.
0 commit comments