Longest Consecutive Number SequenceLoading saved progress…

Longest Consecutive Number Sequence

You're given an unsorted array of integers. Somewhere inside it, some of those numbers line up into a run of consecutive values — like 1, 2, 3, 4 — even though they're scattered all over the array. Your job is to find the longest such run and return its length, not the run itself. The catch: the expected complexity is O(n), so sorting the array first (which is O(n log n)) is too slow.

Signature

// nums: number[] — an unsorted array of integers. May contain duplicates,
//   negatives, and zero. Not sorted, and you must not rely on sorting.
// returns: number — the length of the longest run of consecutive integers
//   (each value one more than the previous) found anywhere in nums.
function longestConsecutiveNumberSequence(nums: number[]): number;

Examples

// [1, 2, 3, 4] is the longest consecutive run → length 4.
longestConsecutiveNumberSequence([100, 4, 200, 1, 3, 2]); // → 4
// The values 0..8 are all present (0 appears twice). They form one run
// of length 9, even though they're shuffled and one is duplicated.
longestConsecutiveNumberSequence([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]); // → 9

Notes

  • The input is unsorted — and you must not sort it. Sorting solves the problem in O(n log n); the target here is O(n).
  • O(n) is the expected complexity. A solution that re-scans for each element (O(n²)) or sorts first (O(n log n)) is slower than required.
  • Duplicates don't inflate the run. [1, 2, 2, 3] has a longest run of 1, 2, 3 → length 3. A repeated value is the same value, not a longer streak.
  • An empty array returns 0. There is no run, so the length is zero.
  • You return the length, not the sequence. [100, 4, 200, 1, 3, 2] returns 4, not [1, 2, 3, 4].
  • Negatives and zero are ordinary integers. A run can be negative, or cross zero, like -2, -1, 0, 1, 2.
Loading editor…