Asked at

Longest Consecutive Sequence

Medium
Verified
SetArrayHash Map~25 min

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

Use a set. Start counting only from values with no predecessor in the set, so each run is walked once — O(n).

The input arrives as a single array nums.

Examples

in[100, 4, 200, 1, 3, 2]
out4

The run 1, 2, 3, 4 has length 4.

in[]
out0

No elements, no sequence.

Constraints

  • 0 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • Target: O(n) time

Get help

🔑

Sign in to solve

Sign in to write, run, and submit your solution — and to pick up where your iOS flow left off.