Skip to content
Advertisement

How does one find the largest consecutive set of numbers in a list that are not necessarily adjacent?

For instance, if I have a list

JavaScript

This algorithm should return [1,2,3,4,5,6,7,8,9,10,11].

To clarify, the longest list should run forwards. I was wondering what is an algorithmically efficient way to do this (preferably not O(n^2))?

Also, I’m open to a solution not in python since the algorithm is what matters.

Thank you.

Advertisement

Answer

Here is a simple one-pass O(n) solution:

JavaScript

The logic may be a little more self-evident if you think in terms of ranges instead of individual variables for the endpoint and run length:

JavaScript
Advertisement