78. Longest consecutive run
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
numbers = [10, 5, 12, 3, 11, 4, 13]4Example 2
numbers = [1, 2, 2, 3]3Example 3
numbers = []0Constraints
numbershas 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).
- Put the numbers in a set:
x + 1 in presentthen takes one step, however many numbers there are. - A run starts at
xexactly whenx - 1is not in the set. From each start, count upward whilex + lengthis there. - Starting only at run starts means each number is counted once in all, so the whole thing is O(n). Counting up from every number would repeat work: n * n steps for one long run.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.