Skip to the content

The longest straight

Problem

You were dealt a messy hand in the tavern card game, the minigame that everyone spends more hours on than saving the kingdom. In it, a straight is a run of values with no gaps, like 4, 5, 6 and 7, and the round goes to the longest straight.

You get cards, a list of positive integers in any order, which can have repeats and can be empty. Return an integer: the length of the longest straight you can build. You don't have to use the whole hand: with [9, 3, 5, 4, 12, 6] you return 4, for 3, 4, 5 and 6, and the 9 and the 12 stay out. A repeated card neither breaks the straight nor makes it longer: [1, 2, 2, 3] gives 3. A single card is already a straight of 1, and with an empty hand you return 0.

Examples

  • Two cards stay out

    [9, 3, 5, 4, 12, 6] → 4

  • Two-digit cards

    [10, 8, 9, 11] → 4

  • One repeated card

    [1, 2, 2, 3] → 3

  • The longest isn't the first you see

    [20, 3, 21, 1, 2, 4] → 4

  • The straight comes last

    [1, 2, 10, 11, 12, 13] → 4

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def longest_straight(cards):
    pass

JavaScript

function longestStraight(cards) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →