Longest Consecutive Sequence

1Medium

Longest Consecutive Sequence

Given an unsorted array of integers nums, return the length of the longest sequence of consecutive elements.

The sequence does not need to appear in order within the array, and the algorithm must run in O(n) time.

Key idea:

  • Put every number in a hash set for O(1) lookups.
  • Only start counting a run from its smallest element — a number n where n - 1 is not in the set.
  • Walk forward with n + 1, n + 2, ... while each exists, tracking the longest run.

Because each number is visited at most twice, the total work is linear.

JR

Jnaneshwara Reddy Satti

Builder · ClearCode

Hi — I'm a 21yo CS grad from India. I built ClearCode while recovering from a surgery, because I genuinely believe DSA should be visual, free, and accessible to everyone. No VC funding. No team. Just me, my laptop, and a lot of chai. ☕

If ClearCode helped you understand even one concept — consider supporting it. Every rupee keeps the servers running and new videos coming.

Support via Razorpay
Support ClearCode ☕