Arrays and hashing · Problem 2 of 3

Longest streak of consecutive ticket numbers

Pattern: Longest Consecutive Sequence in O(n)

mediumNot solved yet

The problem

A raffle sold tickets with whole numbers on them, in no particular order, and some numbers may appear more than once. Write a function that returns the length of the longest run of consecutive ticket numbers that were sold, like 7, 8, 9, 10.

The numbers don't need to be next to each other in the list. Aim for O(n) time: sorting first works, but it's O(n log n).

text
1longest_streak([102, 4, 100, 1, 3, 2])  ->  4
2longest_streak([5, 5, 6])               ->  2
3longest_streak([])                      ->  0
Example 1
102
0
4
1
100
2
1
3
3
4
2
5

1, 2, 3 and 4 were all sold: a streak of 4.

In the first example, the run is 1, 2, 3, 4. In the second, the repeated 5 still counts once.

Write longest_streak(tickets) in Python or longestStreak(tickets) in JavaScript.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 21 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.