Top 150 Interview簡単

Longest Consecutive Sequence

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

問題提起

簡単

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.

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

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

解決する準備はできましたか?

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

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。