Longest Consecutive Sequence
Use a hash set to start counting only from sequence beginnings.
Problem Statement
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.
Examples
Example 1
Explanation: The longest consecutive sequence is [1,2,3,4], length 4.
Example 2
Constraints
- 0 ≤ nums.length ≤ 10⁵
- -10⁹ ≤ nums[i] ≤ 10⁹
Solutions
Sort the array. Iterate and track the current streak length. O(n log n) — violates the O(n) requirement.
Related Concepts
Deepen your understanding with these related topics from our AI Glossary:
Want to master the core concepts?
Our free AI Glossary covers 190+ topics — from Hash Set to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.
Stuck? Ask AI to explain it step by step.
Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.
Free to start · No credit card required to explore
Get Started Free