FastPrepLongest Consecutive Sequence

Longest Consecutive Sequence

Amazon logoAmazon● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Given an unsorted integer array, return the length of its longest sequence of consecutive integer values. Values need not appear consecutively in the input, and duplicate values count once.

The algorithm should run in expected linear time.

Function

longestConsecutive(nums: int[]) → int

Examples

Example 1

nums = [100,4,200,1,3,2]return = 4

The sequence 1,2,3,4 has length four.

Example 2

nums = [0,3,7,2,5,8,4,6,0,1]return = 9

The sequence zero through eight has length nine.

Example 3

nums = []return = 0

Empty input has length zero.

Constraints

  • 0 <= nums.length <= 100000.
  • Values fit in a signed 32-bit integer.

More Amazon problems

See Amazon hiring insights
public int longestConsecutive(int[] nums) {
    // write your code here
}
nums[100,4,200,1,3,2]
expected4
Checking account…