Longest Consecutive Sequence
Given an unsorted array of integers nums
, return the length of the longest consecutive sequence that can be formed. A consecutive sequence is a list of numbers where each element is one more than itβs previous one (no duplicates)
For example, if input array is [4,5,9,3,10,4,7,6,1,9,5]
, the longest consecutive sequence is [3,4,5,6,7]
and return itβs length 5
as answer
1. Sorting
Sorting would bring the equal/consecutive elements closer to each other
Time taken is \( O(n \cdot logn) \) for sorting + \( O(n) \) for traversing array elements
Metric | Complexity |
---|---|
Time | \( O(N \cdot logN ) \) |
Space | \( O(1) \) |
2. Union-Find approach
Consider input nums=[4,5,9,3,10,4,7,6,1,9,5]
The set of unique elements would be: {4,5,9,3,10,7,6,1}
The consecutive sequences formed are:
All elements in a sequence have a predecessor on the left (whose value is one lesser than element), except for the first element (starting value of sequence)
Time:
- To construct set, there are \( n \) insertions, each taking \( O(1) \) time on average i.e. \( O(n) \) for all insertions
- We are starting the inner sequence-exploratory loop only when we find the start of a sequence and it goes on till end of that sequence. Thus, each array element is traversed once by the outer loop and once when itβs respective sequence is explored i.e. \( O(2n) \)
Metric | Complexity |
---|---|
Time | \( O(N ) \) |
Space | \( O(N) \) β¦ for set |