Skip to content
Decoder

Longest Consecutive Sequence

Medium

Problem

Given an unsorted list of integers nums, return the length of the longest run of consecutive values (like 4, 5, 6, 7) that can be formed from its elements. The values do not need to be next to each other in the list. Your solution must run in O(n) time.

Example 1

Input
nums = [100, 4, 200, 1, 3, 2]
Output
4
Why
1, 2, 3, 4

Example 2

Input
nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]
Output
9
Why
0 through 8

Example 3

Input
nums = []
Output
0

Duplicates may appear and count once.

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.