ExamAdda Logo

Longest Consecutive Sequence

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.

Example 1

Input

6
100 4 200 1 3 2

Output

4

Explanation

The longest consecutive sequence is 1, 2, 3, 4. Therefore, its length is 4.

Example 2

Input

10
0 3 7 2 5 8 4 6 0 1

Output

9

Explanation

The longest consecutive sequence is 0, 1, 2, 3, 4, 5, 6, 7, 8. Therefore, its length is 9.

Constraints

0 ≤ nums.length ≤ 10^5
-10^9 ≤ nums[i] ≤ 10^9

Hints:

Hint 1

Store all numbers in a hash set for O(1) lookups.

Hint 2

Start building a sequence only if the current number has no predecessor (num - 1). Then count consecutive numbers to find the longest sequence.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 6, 2026

Last updated

Aug 7, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output