Longest run
medium
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
A run is a set of whole numbers that follow each other with no gaps, like 4, 5, 6, 7.
Given an unsorted list nums, return the length of the longest run you can make using numbers from the list. The numbers don't need to be next to each other in the list.
Examples
Example 1
- Input
- nums = [8, 30, 5, 7, 6, 12]
- Output
- 4
5, 6, 7, 8 is a run of length 4.
Example 2
- Input
- nums = [0, -1, 1, 5]
- Output
- 3
-1, 0, 1 is a run of 3. 5 is on its own.
Example 3
- Input
- nums = []
- Output
- 0
No numbers, no run.
Rules
numshas between 0 and 50,000 whole numbers, which can be negative.- Numbers can appear more than once, but a run uses each value only once.
- Try for a solution that doesn't sort the list.
Words on this page, in plain English (3)Open if any word is new to you
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Length
- How many items a list (or letters a string) has. The last position is always
length - 1. - Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
The list is jumbled, and we're looking for the longest set of numbers that follow on from each other: like 1, 2, 3, 4. Where they sit in the list doesn't matter. We return how long that run is.
2. Solve an example by hand
In [8, 30, 5, 7, 6, 12], you might spot 5, then look for 6 (yes), 7 (yes), 8 (yes), 9 (no). That's a run of 4. 30 and 12 are alone. Answer: 4.
The question you kept asking was "is the next number in the list?".
3. The slow ways
Count up from every number, using includes to check for the next one. Each includes searches the whole list, and for a long run you do it many times from many starting points. On the 50,000-number test that's billions of steps: far too slow.
Sort first. After sorting, runs sit side by side, and one pass counts them. That's O(n log n): a good answer, and fast enough here. The hashing version is a little faster still, and teaches a clever trick.
4. Spot the pattern
"Is this number in the list?" asked over and over: that's a job for a Set. With the numbers in a Set, each check is instant.
But there's a catch. If we count up from every number, a run of 50,000 is counted from 1, then again from 2, then from 3… That's still O(n²). The trick: only start counting at the start of a run. A number n starts a run exactly when n - 1 is not in the Set.
5. The faster idea
- Put every number in a Set.
- For each number
n: ifn - 1is in the Set, skip it, it's in the middle of a run. - Otherwise, count up:
n + 1,n + 2, … while they're in the Set. - Keep the longest length you find.
Count each run from its start
nums
- n =
- –
- length =
- –
- longest =
- 0
function longestRun(nums) { const all = new Set(nums); let longest = 0; for (const n of all) { if (all.has(n - 1)) { continue; // not the start of a run } let length = 1; while (all.has(n + length)) { length++; } longest = Math.max(longest, length); } return longest;}Put every number in a Set, so "is this number in the list?" is instant.
Each number is counted inside exactly one run, from that run's start, so all the counting together takes O(n) steps.
6. The code, line by line
const all = new Set(nums); let longest = 0;new Set(nums)builds the Set in one go, and drops repeats for free.longesttracks the best run so far.for (const n of all) { if (all.has(n - 1)) { continue; // not the start of a run }Loop over the Set (no repeats). If
n - 1exists,nis not where a run starts, socontinuejumps straight to the next number.let length = 1; while (all.has(n + length)) { length++; }nstarts a run. Keep checking the next number,n + length, and grow the run while it's there.longest = Math.max(longest, length);Math.maxkeeps whichever is bigger: the best so far, or this run.
7. How fast is it?
| Count from every number | Sort first | Set, from run starts | |
|---|---|---|---|
| Time | O(n²) or worse | O(n log n) | O(n) |
| Extra memory | O(1) | depends on the sort | O(n) |
The while loop inside the for loop looks like O(n²), but it isn't: the while only runs from run starts, and each number is stepped over once in total. Counting the total work, not just the shape of the loops, is a skill worth practising.
Common mistakes
- Counting from every number. Without the
n - 1check, the code is correct but slow on long runs. - Looping over
numsinstead of the Set. With repeats like[7, 7, 7, …], you'd do the same work again for each copy. - Forgetting the empty list.
longeststarts at 0, so an empty list correctly returns 0.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Longest run
Read the 15 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function longestRun(nums) { const all = new Set(nums); let longest = 0; for (const n of all) { if (all.has(n - 1)) { continue; // not the start of a run } let length = 1; while (all.has(n + length)) { length++; } longest = Math.max(longest, length); } return longest;}