DSA Patterns (Multi-Lang)•Part 2: Arrays, Strings & Hash Maps (6 - 18)
Longest Consecutive Sequence.
In Simple Words:
Put all numbers in a Set. Only start counting a sequence if num - 1 does NOT exist in the set (meaning num is the start of a streak). Then increment num + 1 while present in the set.
- Time: $O(N)$ | Space: $O(N)$
Multi-Language SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef longestConsecutive(nums: list[int]) -> int:
num_set = set(nums)
longest = 0
for n in num_set:
# Check if n is the start of a streak
if (n - 1) not in num_set:
current_num = n
streak = 1
while (current_num + 1) in num_set:
current_num += 1
streak += 1
longest = max(longest, streak)
return longest