Top 150 InterviewEasy

Longest Consecutive Sequence

Detailed guide and Python implementation for the 'Longest Consecutive Sequence' problem.

Problem Statement

Easy

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.

Write a function longestConsecutive(nums: List[int]) -> int.

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

Examples

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

The longest consecutive elements sequence is [1, 2, 3, 4]. Its length is 4.

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

The longest consecutive elements sequence is [0, 1, 2, 3, 4, 5, 6, 7, 8]. Its length is 9.

Need a Hint?
Consider using Arrays & Hashing-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.