algorythms
Arrays & Hashing
LC #128Medium

Longest Consecutive Sequence

Arrays & Hashing
MetaAmazonGoogleBloomberg

Problem

Given an unsorted integer array, return the length of the longest sequence of consecutive integers (e.g. 4,5,6,7). Must run in O(n) — sorting is O(n log n) and won't count. Example: [100,4,200,1,3,2] → 4 because [1,2,3,4] is the longest consecutive run.

arrayhash-setunion-find

Constraints

  • 0 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • O(n) time required

Example

Inputnums = [100, 4, 200, 1, 3, 2]
Output4
Why

Consecutive sequence [1, 2, 3, 4] has length 4

Hints — reveal one at a time