InterviewPrepKit

Home / Coding / Arrays & Hashing

Longest Consecutive Sequence

medium Original β†—
Solving tips
  • Recognize the O(n) bar rules out sorting: put all values in a set for O(1) membership, then grow runs by probing v+1, v+2, ....
  • Key insight: only start a walk from a run's left endpoint (a value v where v-1 is NOT in the set), so each element is visited O(1) times overall.
  • Target O(n) time, O(n) space; without the start-check the walk degrades to O(n^2) on an already-consecutive array β€” exactly the tested case.
  • Pitfall: do membership tests against the set (not the list), and return 0 for the empty array.

Problem

Given an unsorted array of integers nums, return the length of the longest run of consecutive integer values that all appear somewhere in the array. The values only need to exist in the array β€” their positions don’t matter, and duplicates count once.

The required time complexity is O(n) β€” which rules out sorting as the final answer, even though sorting is a fine warm-up.

Examples

Example 1: nums = [100, 4, 200, 1, 3, 2] β†’ 4 The values 1, 2, 3, 4 all appear, forming a consecutive run of length 4; 100 and 200 are isolated.

Example 2: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1] β†’ 9 Every value 0 through 8 appears (the duplicate 0 counts once), a run of length 9.

Example 3: nums = [] β†’ 0 No elements, no run.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

10^5 elements with values up to 10^9: no counting array over the value range, and quadratic scans (~10^10) are out. The O(n) bar is the point of the problem.

Think about it first

Hint 1 If you could ask "is value v in the array?" in O(1), how would you grow a run starting from some value?
Hint 2 Walking upward (v, v+1, v+2, ...) from *every* element re-walks the same run from every one of its members β€” that's O(nΒ²) in the worst case. Which elements are worth starting from?
Hint 3 Put everything in a set. Only start counting from values v where `v - 1` is **not** in the set β€” the run's left endpoint. Every element is then visited O(1) times total across all walks.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.