Skip to contentKEEP THE CRAFTTHE SANCTUARY

Longest Consecutive Sequence

Find the length of the longest run of consecutive integers in an unsorted list.

The problem

Implement Solution.longestConsecutive(nums). nums holds up to 100,000 integers in any order and may contain repeats. Return the length of the longest run of consecutive values x, x + 1, x + 2, ... that all appear in nums. The values do not need to be next to each other in nums. For [100, 4, 200, 1, 3, 2] the answer is 4, from 1, 2, 3, 4. Return 0 for an empty list. Your solution must run in O(n) time, so sorting is not allowed.

Starter code

class Solution:
    def longestConsecutive(self, nums):
        pass

Public examples

  1. nums = [100, 4, 200, 1, 3, 2]gives4
  2. nums = [-4, -2, -3, 8]gives3
  3. nums = [1, 2, 8, 9, 10]gives3

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.