Problem
Problem page: https://leetcode.com/problems/longest-consecutive-sequence/
Topics: Array
Difficulty: Hard
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given[100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is[1, 2, 3, 4]. Return its length:4.Your algorithm should run in O(n) complexity.
Analysis
Given a sequence of ints that isn't necessarily sorted, find numbers in it that form a new sequence. The numbers have to be consecutive, and the new sequence should be as long as possible.
The most obvious approach is to sort the original sequence and then go through it once to find the longest consecutive sequence. The time complexity is O(nlogn)+O(n)=O(nlog(n)), so it doesn't meet the problem's O(n) requirement (by the way, does the original problem mean O(n) time complexity only, or does it require O(n) for both time complexity and space complexity? I'm guessing it's the latter). So I use a hash table. First I go through the original sequence and insert each element into the hash table with the element itself as the key and True as the value. Then I can go through each element in the hash table and search in both directions, checking whether the next consecutive number is in the hash table, to find the longest consecutive sequence. I also set the value of each element I've searched to False so I don't repeat the search for elements in a consecutive sequence I've already searched.
Space complexity is O(n). Time complexity is O(n). Python implements its dictionaries with hash tables, so for now I just use a dictionary for the hash table here.
Be careful not to repeat the search for other elements in the same consecutive sequence.
All in all, this algorithm is pretty hard to think of. Sorting and then going through the sequence is more intuitive and might be the first thing that comes to mind.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-longest-consecutive-sequence/
