HASH-P3

Longest run

Practice 3 of 6Hashing9 tests

The problem

Given a list of whole numbers in any order, return the length of the longest run of consecutive numbers among them. A run is a set of numbers like 4, 5, 6, 7, where each is one more than the one before.

longest_run([100, 4, 200, 1, 3, 2])   # 4  (1, 2, 3, 4)
longest_run([1, 2, 2, 3])             # 3  (repeats once)
longest_run([])                       # 0

Sorting would make this easy, but it costs O(n log n). Do it in O(n) on average. sorted() and .sort() are switched off.

Limits

  • Up to 200,000 numbers.

Builds on HASH-5 Inside dict and set and HASH-6 Counting and grouping.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1ClassicNot run
2EmptyNot run
3One numberNot run
4RepeatsNot run
5Negative numbersNot run
6Two runsNot run
7No two in a rowNot run
8200,000 in one runNot run
9200,000 scatteredNot run