KatInterview

Length of the Longest Run of Consecutive Integers

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashinghash-setarrayssequences

Last updated

Tests whether a candidate can find the longest chain of consecutive integers in an unsorted array in linear time using a hash set.

Longest Chain of Consecutive Values

You are given an unsorted array of integers. Your task is to find the length of the longest chain of consecutive integers that all appear somewhere in the array — regardless of where they sit in it.

For example, if the array contains the values 1, 2, 3, and 4 scattered across various positions, that chain has length 4.

Rules

  • Order does not matter. Only the values count, not their positions in the array.
  • Duplicates count once. If the same value appears more than once it contributes a single slot to any chain it belongs to.
  • Negative numbers and zero are valid inputs.
  • Return 0 for an empty array.
  • Your solution must run in O(n) time.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Element values may repeat.
  • You may not assume the array is sorted.

Examples

Example 1

Input: longest_consecutive_chain([100, 4, 200, 1, 3, 2])

Output: 4

Example 2

Input: longest_consecutive_chain([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])

Output: 9

Hints

Hint 1

Load all values into a hash set first. Membership checks become O(1), and duplicates disappear automatically.

Hint 2

A chain has exactly one starting point — the smallest value in it. A value starts a chain only when the integer just below it is absent from the set. Use that fact to avoid re-walking the same chain from every element inside it.

Hint 3

Once you find a chain start, keep stepping one integer upward and count how far you can go before hitting a value that is missing from the set. Track the longest count seen across all chain starts.