InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Arrays & Hashing

Longest Consecutive Sequence

medium Original ↗ 00:00

Problem

Given an unsorted array of integers nums, return the length of the longest run of consecutive integer values that all appear somewhere in the array. The values only need to exist in the array — their positions don’t matter, and duplicates count once.

The required time complexity is O(n), which rules out sorting as the final solution.

Examples

Example 1: nums = [100, 4, 200, 1, 3, 2]4 The values 1, 2, 3, 4 all appear, forming a consecutive run of length 4; 100 and 200 are isolated.

Example 2: nums = [0, 3, 7, 2, 5, 8, 4, 6, 0, 1]9 Every value 0 through 8 appears (the duplicate 0 counts once), a run of length 9.

Example 3: nums = []0 No elements, no run.

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

With up to 10^5 elements and values up to 10^9, a counting array over the value range is infeasible, and quadratic scans (~10^10 operations) are too slow. The O(n) requirement is the core constraint.

Think about it first

Hint 1 If you could ask "is value v in the array?" in O(1), how would you grow a run starting from some value?
Hint 2 Walking upward (v, v+1, v+2, ...) from *every* element re-walks the same run from every one of its members — that's O(n²) in the worst case. Which elements are worth starting from?
Hint 3 Put everything in a set. Only start counting from values v where `v - 1` is **not** in the set — the run's left endpoint. Every element is then visited O(1) times total across all walks.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug