Skip to content

Longest Consecutive Sequence

MediumPython 3Union-findHash tablesArrays

You are given an unsorted list of integers nums. Return the length of the longest run of consecutive integers that can be formed from its values, in any order. Duplicates count only once.

Sorting makes this easy at O(n log n); the expected solution runs in O(n).

Constraints:
  - 0 <= len(nums) <= 10^5
  - values may be negative and may repeat
Examples:
  [100, 4, 200, 1, 3, 2]           -> 4   (1, 2, 3, 4)
  [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]   -> 9   (0 through 8)
  [1, 1, 1]                        -> 1
  []                               -> 0

Python 3, run in your browser. Run tests runs the problem's own tests with a free account; the AI interviewer reads your code and your runs in a practice interview.

Loading the editor…