Applied AI Engineer (LLM) coding learning path Level 2 This level · 2 of 31

Longest Consecutive Sequence

Medium Hash map

Problem

Given an unsorted integer array, return the length of the longest run of consecutive integers (like 1,2,3,4) whose values appear in the array, in any order. The original asks for O(n) time.

Original: LeetCode 128: Longest Consecutive Sequence.

Examples

Example 1

Input`nums = [100, 4, 200, 1, 3, 2]`
Output`4`

Example 2

Input`nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]`
Output`9`

Example 3

Input`nums = []`
Output`0`

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 128: Longest Consecutive Sequenceleetcode.com
  2. Java SE 17 API: HashSetdocs.oracle.com
Previous
Next