Longest Reading Streak

Hardhash mapAlso known as Longest Consecutive Sequence

A reading app numbers days from its launch: day 0 is launch day, day 1 the day after, and people who tested it early have negative days. Every time you read, the app logs the day number. The log syncs from your phone and your tablet, so it arrives jumbled, and a day you read twice appears twice.

The app wants to show your best ever streak: the longest run of back-to-back days on which you read at least once.

Your task

Write longestStreak(days). Return the length of the longest run of consecutive whole numbers d, d + 1, ..., d + L - 1 that all appear in days. Repeated day numbers count once.

An empty log returns 0. Aim for O(n) time: sorting works but costs O(n log n).

longestStreak(days: int[]) → int

Examples

Example 1
Input
days = [12, 4, 10, 5, 11, 13, 3, 11]
Output
4
Why

Days 10, 11, 12, 13 make a streak of 4. Days 3, 4, 5 make a streak of 3. Day 11 appears twice, but it is still one day, so the answer is 4, not 5.

Example 2
Input
days = [-1, 7, 1, 0, -2]
Output
4
Why

Days -2, -1, 0, 1 are back to back, a streak of 4 that runs across launch day. Day 7 stands alone.

Example 3
Input
days = []
Output
0
Why

No reading at all, so the best streak is 0.

Constraints

  • 0 ≤ days.length ≤ 100,000
  • -1,000,000,000 ≤ days[i] ≤ 1,000,000,000
Start with brute force

For each day, count upward from it, checking whether d + 1, d + 2 and so on appear by scanning the log each time.

Each check is a scan of n entries, and a single long streak gets recounted from every one of its days. That is O(n³) in the worst case, hopeless for 100,000 entries. Even with a set to make each check O(1), starting from every day still recounts a streak of length L about L²/2 times: one streak of 100,000 days costs 5 billion steps.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code