Sub topic 5
Finding the longest streak
The current streak tells you where you are now. The longest streak tells you the best you have done so far. This chapter builds longest_streak, explains why it works, and covers the inputs that can break it.
This chapter assumes you have read the earlier chapters on the check-in data model and the current streak. You should be comfortable with these:
- Python sets,
sorted(), and loops. dateandtimedeltafrom thedatetimemodule.- The data model: each habit maps to a
setofdateobjects, one per day it was done.
What the longest streak measures
A streak is a run of consecutive calendar days, each with a check-in. The longest streak is the length of the longest such run anywhere in the history of a habit.
It differs from the current streak in two ways:
- The current streak is anchored at today (or yesterday). It looks backwards from a known point and stops at the first gap.
- The longest streak has no anchor. A run from last March counts as much as one from this week, so you have to examine the whole history.
Two facts follow from the definitions, and both are useful for testing:
longest_streak(days) >= current_streak(days)always holds, because the current streak is one of the runs being compared.- The two values are equal when your best run is the one you are on now.
The approach: sort, then scan once
A set has no order, so you cannot walk through it and expect days to arrive in calendar order. Sorting the dates fixes that. After sorting, any two consecutive runs of days sit next to each other in the list, and each date only needs to be compared with the one before it.
For each date in sorted order, there are two cases:
- It is exactly one day after the previous date. The current run grows by one.
- It is not. This is the first date, or there is a gap. A new run starts with length 1.
After each date, you update the best length seen so far.
The implementation
from datetime import timedelta
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return bestSome details are worth noting:
bestandrunboth start at 0. For an empty set the loop body never runs and the function returns 0, which is the right answer for a habit with no check-ins.previousstarts asNoneso the first date does not need a special comparison. Theprevious is not Nonecheck short-circuits before the subtraction.- On a gap the run resets to
1, not0. The date you are looking at is itself a logged day, so it is the first day of a new run of length 1. day - previousproduces atimedelta. Comparing it withtimedelta(days=1)is exact fordateobjects, because dates have no time component.
Tracing an example
Suppose a habit was logged on these days in March 2026: the 1st, 2nd, 3rd, 5th, 6th and 9th. The sorted scan looks like this:
| Date | Gap from previous | run | best |
|---|---|---|---|
| 2026-03-01 | none (first date) | 1 | 1 |
| 2026-03-02 | 1 day | 2 | 2 |
| 2026-03-03 | 1 day | 3 | 3 |
| 2026-03-05 | 2 days | 1 | 3 |
| 2026-03-06 | 1 day | 2 | 3 |
| 2026-03-09 | 3 days | 1 | 3 |
The best run is the three days from March 1 to March 3, so the function returns 3. Here it is as runnable code:
from datetime import date, timedelta
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return best
days = {
date(2026, 3, 1), date(2026, 3, 2), date(2026, 3, 3),
date(2026, 3, 5), date(2026, 3, 6),
date(2026, 3, 9),
}
print(longest_streak(days)) # 3Why the sort matters
If you skip sorted() and loop over the set directly, the result depends on the order in which Python happens to yield the dates. Sometimes that order looks sorted, so the code appears to work in a quick test and then fails on other data. This is a common intermittent bug.
Sorting costs O(n log n) time for n check-ins. For a personal tracker, even ten years of daily check-ins is about 3,650 dates, so the cost is negligible. You do not need a faster algorithm to use this one, but a linear one exists, and it is worth seeing.
A linear alternative: start only at run beginnings
Instead of sorting, you can use the set's fast membership test. A date begins a run exactly when the day before it is not in the set. For each such start, count forward until the run ends.
from datetime import timedelta
def longest_streak_linear(days):
best = 0
for day in days:
if day - timedelta(days=1) not in days: # this date starts a run
length = 1
while day + timedelta(days=length) in days:
length += 1
best = max(best, length)
return bestEach date is visited once by the outer loop. It is visited again by the inner while loop only if it belongs to a run, and only as part of the one run that started before it. Total work is O(n). This approach requires days to be a real set (or another type with O(1) membership), because the lookups would be slow on a list.
The two versions compare as follows:
| Row | Sort and scan | Start-of-run counting |
|---|---|---|
| Time | O(n log n) | O(n) |
| Needs a set | No, any iterable of dates | Yes, for fast lookups |
| Easy to extend to report the run's dates | Yes | Yes, with a little work |
| Reads like the problem | Mostly | Needs a sentence of explanation |
For this tracker, use the sorted version as the main implementation. It is the one in the plan, it also works if the history later arrives as a list, and the performance difference does not matter at this size. The linear version is useful as a second opinion in tests, which comes up below.
Reporting which run was the longest
A number alone does not say when your best period was. Knowing the dates helps in the review step later in the tutorial: you can ask what was different about that month. Here is a variant that returns the length together with the first and last date of the best run.
from datetime import timedelta
def longest_run(days):
"""Return (length, first_day, last_day) of the longest run, or (0, None, None)."""
best_len = 0
best_start = best_end = None
run = 0
run_start = previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
run_start = day
if run > best_len:
best_len, best_start, best_end = run, run_start, day
previous = day
return best_len, best_start, best_endThe comparison is run > best_len, not >=. When two runs tie, the earlier one is kept. If you would prefer the most recent one on a tie, change the comparison to >=. Whichever you choose, write it down in a comment, because it is a decision and not an accident.
Edge cases
| Input | Result | Why |
|---|---|---|
| Empty set | 0 | The loop never runs. |
| One date | 1 | The first date starts a run of 1. |
| Same day logged twice | Counted once | The set already removed the duplicate in `check_in`. |
| Dates added out of order | Correct | `sorted()` fixes the order. |
| Month or year boundary | Correct | `timedelta` arithmetic handles it, for example 2026-02-28 to 2026-03-01. |
| Leap day | Correct | 2028-02-28, 2028-02-29 and 2028-03-01 form a run of 3. |
Gotcha: datetime values instead of dates
datetime is a subclass of date, so a datetime can end up in the set without any error. Two problems follow:
- Two
datetimevalues on the same calendar day but at different times are different set members. The "no duplicates" guarantee fromcheck_inis gone. - A run is broken if the second value is 23 hours and 59 minutes after the first, because the difference is not exactly one day. Likewise, 24 hours and 1 minute is not exactly one day either.
The fix is to store only dates. If a datetime comes in from elsewhere, convert it with .date() before storing it.
from datetime import datetime, date
stamp = datetime(2026, 3, 1, 21, 30)
day = stamp.date()
print(day == date(2026, 3, 1)) # TrueGotcha: future dates
The function does not know what today is, so a date in the future is counted like any other. If a typo logs 2062-03-01 instead of 2026-03-01, that single date forms a run of 1 and usually does no harm. A typo that extends a real run is harder to spot. If your data entry allows it, reject dates later than today in check_in, not in the streak code. The streak functions should stay pure calculations on whatever dates they are given.
Testing the function
Streak code is easy to get subtly wrong, and it is cheap to test because it needs no files or clock. This script checks the cases above, compares the two implementations on random data, and confirms the invariant that the longest streak is never shorter than the current one.
import random
from datetime import date, timedelta
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return best
def longest_streak_linear(days):
best = 0
for day in days:
if day - timedelta(days=1) not in days:
length = 1
while day + timedelta(days=length) in days:
length += 1
best = max(best, length)
return best
def current_streak(days, today=None):
today = today or date.today()
day = today if today in days else today - timedelta(days=1)
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streak
# Fixed cases
assert longest_streak(set()) == 0
assert longest_streak({date(2026, 3, 1)}) == 1
assert longest_streak({date(2026, 2, 28), date(2026, 3, 1)}) == 1
assert longest_streak({date(2028, 2, 28), date(2028, 2, 29), date(2028, 3, 1)}) == 3
# Random cross-check and invariant
random.seed(7)
start = date(2026, 1, 1)
for _ in range(500):
days = {start + timedelta(days=random.randrange(60)) for _ in range(random.randrange(40))}
today = start + timedelta(days=random.randrange(60))
assert longest_streak(days) == longest_streak_linear(days)
assert longest_streak(days) >= current_streak(days, today)
print("all checks passed")Passing a fixed today to current_streak keeps the test repeatable. Without it, the result would change every day the test runs.
Using the number
On its own, the longest streak is a record to beat, and records can mislead. Some points to keep in mind for the review chapter:
- A long record and a short current streak together mean you once had the habit working and lost it. That is a signal to ask what changed.
- A current streak equal to the longest streak means you are in your best run right now.
- A streak counts only perfect consecutive days. A person who does a habit six days out of seven has a longest streak of 6 at most, even though the habit is going well. The completion rate in the next chapter measures that better.
The two numbers answer different questions, so read them together.
Exercise
Change longest_run so that, when two runs tie for the longest, it returns the most recent one. Then say what longest_run returns for the dates 2026-03-01, 2026-03-02, 2026-03-10 and 2026-03-11 before and after your change.
Show answer
Change the test if run > best_len: to if run >= best_len:. A tie then replaces the stored best, so the later run wins. Before the change the result is (2, date(2026, 3, 1), date(2026, 3, 2)), because the first run of length 2 is kept. After the change it is (2, date(2026, 3, 10), date(2026, 3, 11)).
Exercise
A friend writes longest_streak without calling sorted(), looping directly over the set. Their tests pass on small examples. Explain why the function is still wrong and give a small input that can make it fail.
Show answer
A set has no guaranteed order, so the loop may visit dates out of calendar order. The code then compares a date with a previous date that is not its calendar neighbour, which breaks runs or measures them incorrectly. The small tests passed only because the dates happened to arrive in order. Any set of dates whose iteration order differs from calendar order can fail, for example {date(2026, 3, 3), date(2026, 3, 1), date(2026, 3, 2)} if it is visited in that order. The first step compares 3 March with nothing, the second sees 1 March (not one day later) and resets, and the third sees 2 March (one day later), so the function returns 2 instead of 3. Adding sorted(days) removes the dependence on set order.