100 XP

78. Longest consecutive run

Advanced sets

Write a function longest_run(numbers) that takes a list of whole numbers in any order and returns the length of the longest run of consecutive values it contains: numbers like 10, 11, 12, 13, each one more than the last.

  • The numbers can be anywhere in the list: their order doesn't matter, only which values are there.
  • A value that appears more than once counts once: [1, 2, 2, 3] has the run 1, 2, 3, of length 3.
  • An empty list has no run, so the answer is 0.

Sorting first works, but takes O(n log n). A set can do it in O(n), if you start counting only where a run starts.

Example 1

Inputnumbers = [10, 5, 12, 3, 11, 4, 13]
Output4
Explanation10, 11, 12 and 13 are all there.

Example 2

Inputnumbers = [1, 2, 2, 3]
Output3
Explanation1, 2, 3: the repeated 2 counts once.

Example 3

Inputnumbers = []
Output0
ExplanationNo numbers, no run.

Constraints

  • numbers has 0 to 300 whole numbers, each from -10^9 to 10^9.

Submit also runs 9 more tests you can't see.

Practises Sets (lesson 12).

Code
def longest_run(numbers):
    """Find the longest run of consecutive values.

    numbers: list of int, in any order; may be empty
    Returns: int, the length of the longest run of values
        that follow on one by one
    """
    # Write your code here
    pass