/128. Longest Consecutive Sequence

128. Longest Consecutive Sequence

Medium
Arrays47% acceptance

Given an unsorted list of integers input_array, return the length of the longest sequence of consecutive integers that can be formed from input_array. Consecutive integers are those where each integer is exactly one greater than the previous. The sequence does not need to be contiguous in input_array. The algorithm must run in O(n) time.

Example 1

Input: [5, 2, 3, 1, 4, 8]

Output: 5

Explanation: The longest consecutive sequence is [1,2,3,4,5], length 5.

Example 2

Input: [10, 11, 13, 12, 15, 14]

Output: 6

Explanation: The longest consecutive sequence is [10,11,12,13,14,15], length 6.

Example 3

Input: [20, 21, 23, 25, 24]

Output: 3

Explanation: The longest consecutive sequence is [23,24,25], length 3.

Constraints

  • 1 <= len(input_array) <= 105
  • -109 <= input_array[i] <= 109 for all valid i
Python (current runtime)

Case 1

Input: [9, 8, 7, 6, 5, 4, 3]

Expected: 7

Case 2

Input: [100, 101, 102, 104, 105]

Expected: 3

Case 3

Input: [0, -1, -2, -3, 2, 1]

Expected: 4

Case 4

Input: [50]

Expected: 1

Case 5

Input: [1, 3, 5, 7, 9]

Expected: 1