There are a lot of algorithms available to solve the problems with an efficient solution. Learning some such algorithms and practicing some quality problems may help one to increase problem-solving skills and crack many technical interviews with ease. In this article let us look into a medium-level array problem Longest Consecutive sequence with a solution.
We are given an unsorted array of integers, we have to find the longest consecutive sequence in the array.
- First, sort the array using any one of the in-place sorting algorithms.
- Then declare two variables to track the current length and maximum length of consecutive numbers found in the array.
- If the length of the array is zero then return zero as the output
- Else, iterate through the array and check whether the next element to the current element is consecutive and increment the current value.
- If the next element is not consecutive to the current element then stop the iteration.
- Compare and check the current and longest, and store the maximum value in the longest.
- Repeat the steps till the length of the array.
- The final value in the longest variable is the result.
Example of Longest Consecutive Sequence
To understand the working of our approach better, let us take an example and look into the step-by-step execution.
In the first step, the input is sorted in increasing order.
Then at each step, the current element is checked with the next element to verify whether it is a consecutive number. Then the current and longest variables are incremented. Finally, the maximum length is returned as output. Refer to the below image for a better and clear understanding of the steps.
Implementation of Longest Consecutive Sequence in Java
Implementation of Longest Consecutive Sequence in C++
The execution time varies according to the input values has to be analyzed for the solution we build to check the efficiency of the approach. For our solution, the respective time complexity will be O(nlogn). Since the sorting algorithm takes the logarithmic time complexity and we are iterating through a single loop.
The extra space required to execute the program is the space complexity of the program. In our case, we are using the in-place sorting algorithm for arranging the elements and no new array is used so the space complexity will be O(1). That is constant space complexity which remains constant irrespective of the input size.
In this article, we have solved a medium-level problem related to arrays. This problem can also be solved with data structure concepts like a heap. We have covered C++ and java codes but if you want to learn how to find the longest consecutive sequence in python our online python tutors are available 24/7 to assist you.