Skip to content
Algorithms for Beginners

Problems / Hashing and counting

Longest run

medium

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. 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

  1. Example 1

    Input
    nums = [8, 30, 5, 7, 6, 12]
    Output
    4

    5, 6, 7, 8 is a run of length 4.

  2. Example 2

    Input
    nums = [0, -1, 1, 5]
    Output
    3

    -1, 0, 1 is a run of 3. 5 is on its own.

  3. Example 3

    Input
    nums = []
    Output
    0

    No numbers, no run.

Rules

  • nums has 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.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function longestRun(nums) {
  // Return the length of the longest run.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in hashing and counting

  • Learn the hashing and counting pattern

    Remember what you have seen in a Map, so you never search for it twice.

  • Pair to target

    Easy. Find the two items whose prices add up to exactly the value of a gift card.

  • Spot a repeat

    Easy. Check whether any raffle ticket number was printed more than once.

  • Letter twins

    Easy. Decide whether one word can be made by rearranging all the letters of another.

  • First lonely letter

    Easy. Find the position of the first letter that appears only once in a piece of text.

  • Group the twins

    Medium. Sort a list of words into groups, where every word in a group uses exactly the same letters.