Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Arrays and hashing

Longest run of consecutive integers

Medium · Target 15 minutes · Arrays and hashing · Type asked atTwo SigmaCitadel

Given an unsorted array nums, return the length of the longest run of consecutive integers that appear in it. The numbers need not be adjacent in the array, and duplicates do not lengthen a run.

For [100, 4, 200, 1, 3, 2] the answer is 4, from the run 1, 2, 3, 4.

Examples

InputOutputWhy
nums = [100, 4, 200, 1, 3, 2]41, 2, 3, 4 are all present. 100 and 200 are islands.
nums = [9, 1, 8, 2, 7, 3]31, 2, 3 is the longest. 7, 8, 9 is also length 3 — either is fine, the answer is the length.
nums = [5, 5, 5]1Duplicates do not extend a run.

Constraints

  • 0 ≤ n ≤ 10⁵
  • −10⁹ ≤ nums[i] ≤ 10⁹
  • The array is not sorted
  • Values may repeat

Hints

Hint 1

Sorting works and costs O(n log n). Before you reach for it, ask what a sort actually buys you here — you never need the order, only whether a particular value is present.

Hint 2

Put everything in a hash set. Now "is x + 1 present?" is O(1). What is left is deciding where to start counting.

Hint 3

Only start counting at a value that begins a run — one whose predecessor is absent. That single test is what keeps the whole thing linear.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.