Question

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.

This is an arrays question.

Idea

  • We want to turn the list into a set for O(1) indexing
  • We iterate for every num in nums
    • Try to find the start of a sequence (does num - 1 exist in the set)
      • If you do find a start, keep count of the longest streak until the sequence runs out (does curr_num + 1 exist?)
      • Update the current number
    • Update the max sequence

Solution