Given an input array nums our function should return the length of the longest consecutive sequence that can be formed. A consecutive sequence is a sequence of elements in which each element is exactly 1 greater than the previous element. The elements in the input array don’t have to be in consecutive order
Our solution should run in O(n) time complexity
Example
Approach 1
Visualize the problem
Solve without code
To start we can iterate through the input array
Checking each time if the current number has a neighbor value of num - 1
If not then we know this is a start of a sequence
Then we check if num + 1 exists until we can’t
This run defines one sequence and we kept track of how many numbers define this sequence
Once we’ve counted all sequences we can find the max count value we defined
Solve with code
Convert our input array to a hash set to reduce the time complexity of looking up values to O(1)
Create our max count variable to keep track of the max count
Begin iterating through the set
If our current number does not have a neighbor of num - 1 in the set then we know this is the start of a sequence
We can then check if num + 1 exists in the set until we can’t
Update our max count to the count of this sequence
We move to the next number in the set and check for the same conditions