PIXELBANKv8.2.1
Menu

Longest Consecutive Sequence

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

You must write an algorithm that runs in O(n) time.

Example:

Input:
100,4,200,1,3,2
Output:
4
Reasoning:
  • First, we store the input values in a set for O(1) lookup: {100, 4, 200, 1, 3, 2}
  • Then, we iterate over the set and check if the current number is the start of a sequence (i.e., num - 1 is not in the set)
  • For each sequence start, we count the consecutive numbers: 1 is a sequence start and its consecutive numbers are 2, 3, and 4, so the sequence length is 44
  • The final output is the maximum sequence length found, which is 44

Constraints:

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
Editor

Test Results

0/0
Run code to see test results.