Back to questions
Given an array of integers , return the length of the longest consecutive sequence of elements that can be formed from the array.
A consecutive sequence consists of elements where each element is exactly greater than the previous element. The elements in the sequence can be selected from any position in the array and do not need to appear in their original order.
Input:
Output:
Explanation: The longest consecutive is which have a length of
Input:
Output:
Explanation: The longest consecutive is which have a length of
This isn't a HARD problem, but it's one that has multiple solutions. Your interviewer might have you solve it one way and then ask you to propose other options while comparing their strengths and weaknesses.
Let's explore three different ways to solve this problem and compare them.
In interviews, it's always a good idea to start with the brute force approach and build upon it. That's also what the interviewer expects from you.
For our case, what if we start from each number in the list and keep going while the numbers are consecutive? The main question is: how can we tell if the numbers are consecutive?
One way is to check if the current number plus exists in the array. If it does, that means we can keep going. We update the current number and keep checking for the next one.
For fast lookup, we'll use a set, since checking if an element exists in a set takes time.
Here's is the summary of what we are gonna do:
Here's the code to do that:
This solution has time complexity because we start a new sequence from every number. For example, if we have numbers from to , the algorithm starts a new sequence at each of them, making the time complexity ≈ .
The previous solution has two inefficiencies:
Here's the code to do that:
In the worst case, we iterate at most twice over the set (once for iterating, once for counting sequences), making the time complexity .
Another way to solve this problem is by sorting the list. If we sort it, all consecutive numbers will be placed next to each other. Then, we can iterate through the sorted list and count the length of each consecutive sequence. The longest such sequence will be our answer.
Here's the corrected and optimized code: