Longest Consecutive Sequence
Given an array of integers nums, return the length of the longest consecutive sequence of elements.
A consecutive sequence is a sequence of elements in which each element is exactly 1 greater than the previous element.
You must write an algorithm that runs in O(n) time.
Example 1:
Input: nums = [2,20,4,10,3,4,5]
Output: 4
Explanation: The longest consecutive sequence is [2, 3, 4, 5].
Example 2:
Input: nums = [0,3,2,5,4,6,1,1]
Output: 7
Constraints:
0 <= nums.length <= 1000
-10^9 <= nums[i] <= 10^9
Solution
According to example 2, we can know that “sequence” here can shuffle the original order in the input array. Therefore, the order and number of the numbers in input array is not important, and we can just store them in a set()
for easy searching.
After that, we can do a Memorized Search, record the longest sequence length of each number when the number is as the start number of the sequence. We can store this in a dictionary, where the key is the number and the value is the longest sequence length. Therefore, we can directly get the length of next consecutive number if the next number has already been searched. This will reduce the time complexity of search from O ( n 2 ) O(n^2) O(n2) to O ( n ) O(n) O(n)
Code
To write the process elegantly, I realize it by DFS.
If the number has been searched, then its longest sequence value will appear in the dictionary, just return it;
If the number has not been searched, check if the next consecutive number exists.
If the next number exists, go to the next one and return 1+returned value, or just return 1.
class Solution:
def longestConsecutive(self, nums: List[int]) -> int:
num_set = set(nums)
length_dict = {}
def dfs(number: int) -> int:
if number in length_dict:
return length_dict[number]
if number+1 not in num_set:
length_dict[number] = 1
return length_dict[number]
length_dict[number] = dfs(number+1) + 1
return length_dict[number]
answer = 0
for num in num_set:
if num not in length_dict:
answer = max(answer, dfs(num))
return answer