v9.1.1
Menu

Longest Consecutive Sequence

mediumFREEHash Maps & SetsApple DSA

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
  • nums is an unordered list of integers; only which values are present matters, not where they sit. A consecutive sequence is a run of values v,v+1,…,v+k−1v, v+1, \dots, v+k-1 that all appear in nums, and its length is kk.
  • The sample values are {100,4,200,1,3,2}\{100, 4, 200, 1, 3, 2\}. Placed on a number line they form three separate runs: 1,2,3,41, 2, 3, 4 (length 44), 100100 alone (length 11) and 200200 alone (length 11).
  • The run 1…41 \dots 4 ends where it does because 00 and 55 are missing; 100100 is isolated because neither 9999 nor 101101 appears.
  • The answer is the length of the longest run: the largest of 4,1,14, 1, 1 is 44, matching the output 4.
  • Notice the run's members are scattered through the input, so adjacency in nums is irrelevant. Repeated values count once: the list 0,3,7,2,5,8,4,6,0,10, 3, 7, 2, 5, 8, 4, 6, 0, 1 holds two zeros, yet its run 0…80 \dots 8 has length 99. An empty list gives 00.

Constraints

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

More from Apple DSA

solution.py

Test results

Sign in to run your code against the test cases.