Editor

Longest Consecutive Run

#136 · Dictionaries and sets · Advanced · 125 XP · about 20 min

Write longest_run(nums) that returns the length of the longest run of consecutive integers (like 4, 5, 6, 7) whose values all appear somewhere in nums.

The list is not sorted, the run can use the numbers in any order, and a repeated number counts once.

Examples

longest_run([100, 4, 200, 1, 3, 2])          # returns 4
longest_run([0, 3, 7, 2, 5, 8, 4, 6, 0, 1])  # returns 9
longest_run([])                              # returns 0

In the first example the run is 1, 2, 3, 4.

Constraints

  • 0 <= len(nums) <= 100,000
  • Values are between -10**9 and 10**9

Note

Sorting works, but there is a way that looks at each number only a few times and never sorts. Try to find it.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.