Longest consecutive sequence#

Levels: level-5
Data structures: array
Patterns: union-find

LeetCode

Description#

  • Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
  • Your algorithm should run in O(n) complexity.

Example#

text
1Input: [100, 4, 200, 1, 3, 2]
2Output: 4
3Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Python Solution#

py
 1class Solution:
 2    def longestConsecutive(self, nums):
 3        longest_streak = 0
 4        num_set = set(nums)
 5
 6        for num in num_set:
 7            if num - 1 not in num_set:
 8                current_num = num
 9                current_streak = 1
10
11                while current_num + 1 in num_set:
12                    current_num += 1
13                    current_streak += 1
14
15                longest_streak = max(longest_streak, current_streak)
16
17        return longest_streak