Longest Consecutive Integer Run in O(N) Time

Difficulty: Hard · Unit 3: Built-in Data Structures & Hashing · Featured in: Tough Challenge

Given an unsorted array of N integers (duplicates allowed), return the length of the longest consecutive elements sequence in O(N) average time without sorting.

Input & Output Format

Input: Line 1: integer N. Line 2 (if N > 0): N space-separated integers.

Output: Print a single integer length.

Sample 1

6
100 4 200 1 3 2
4

Longest consecutive sequence is [1, 2, 3, 4] of length 4.

Free forever — sign in with email at poorvithmp.com to unlock the dry run, verified Python 3 solution, edge-case traps, and downloads.

Back to Python Notes Hub