Member-only story

Longest Consecutive Sequence

Given an array of integers. Find the length of the longest sub-sequence such that elements in the sub-sequence are consecutive integers, the consecutive numbers can be in any order.

Paresh Krishna Sharma
3 min readJan 8, 2022

If you are here then chances are you’re trying to find the longest consecutive sequence in an array of integers. The problem can be visualized as follows:

Source: GeeksForGeeks

The above problem could have multiple solutions, but here we will be using a simple approach with O(N) complexity. Here, we will use Tree-Set from Java Collections which are set but store the values in their natural order by sorting them internally at the time of insertion. Although, some might think that sorting while inserting will be done at higher cost of time complexity. But this is the magic of Tree-Set which provides the same implementation in O(log N) times.

How Tree-Set implements insertion in O(log N) ?

In Tree-Set, a self-balancing binary search tree is employed (Red-Black Tree). Therefore, sorting is achieved in the above time complexity while insertion.

Back to our problem, we will insert all our elements of array into a Tree-Set as below:

--

--

Paresh Krishna Sharma
Paresh Krishna Sharma

Written by Paresh Krishna Sharma

Unleashing the Power of Code, Data, and Creativity ✨ | Software Engineer at Microsoft | LinkedIn : www.linkedin.com/in/itsparesh

No responses yet