Longest Reading Streak

Hardhash mapAlso known as Longest Consecutive Sequence

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

The app shows your best streak: the longest run of back-to-back days with at least one read.

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 a streak of 3. Day 11 appears twice but is 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 make a streak of 4 across launch day. Day 7 stands alone.

Example 3
Input
days = []
Output
0
Why

No reading, 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, scanning the log to check whether d + 1, d + 2 and so on appear.

Each check scans n entries, and a long streak is recounted from every one of its days: O(n³) in the worst case, hopeless for 100,000 entries. Even with a set, starting from every day recounts a streak of length L about L²/2 times: one 100,000-day streak 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