Longest Daily Purchase Streak for Each Customer
Arrays & HashingAuto-graded · 14 test casesLast updated
Group purchase records by customer, collapse same-day duplicates, and find the longest run of back-to-back calendar days, reporting results sorted by customer id.
Longest Daily Purchase Streak
An online store keeps a log of purchases. Each record is a dictionary with these keys:
id: the purchase identifier (an integer).user_id: the customer who made the purchase (an integer).order_date: the calendar date of the purchase, as a string inYYYY-MM-DDformat.
For loyalty reporting, you must find each customer's best streak: the largest number of consecutive calendar days on which that customer made at least one purchase.
Task
Implement a function that takes the list of purchase records and returns, for every customer that appears in the log, a pair [user_id, best_streak].
Rules
- A streak is a block of dates in which each date is exactly one calendar day after the previous one. Real calendar adjacency applies, so
2024-01-31followed by2024-02-01,2024-02-28followed by2024-02-29in a leap year, and2023-12-31followed by2024-01-01are all consecutive. - Several purchases by the same customer on the same day count as a single day. They neither lengthen nor break a streak.
- The records can arrive in any order.
- Every customer in the output has at least one purchase, so each
best_streakis at least 1. - Return the pairs sorted by
user_idin ascending order, with exactly one pair per customer. - If the input list is empty, return an empty list.
Constraints
0 <= len(orders) <= 10^5user_idis an integer.order_dateis always a valid date inYYYY-MM-DDformat.- The return value is a list of
[user_id, best_streak]lists, sorted byuser_id.
Examples
Example 1
Input: longest_purchase_streaks([{'id': 1, 'user_id': 101, 'order_date': '2024-01-01'}, {'id': 2, 'user_id': 101, 'order_date': '2024-01-02'}, {'id': 3, 'user_id': 101, 'order_date': '2024-01-05'}, {'id': 4, 'user_id': 102, 'order_date': '2024-01-03'}, {'id': 5, 'user_id': 102, 'order_date': '2024-01-04'}])
Output: [[101, 2], [102, 2]]
Hints
Hint 1
Several purchases on one day should count only once, so think about which collection type removes duplicates for you.
Hint 2
After deduplicating and sorting one customer's dates, a streak continues only when the gap to the previous date is exactly one day. Otherwise it restarts at 1.
Hint 3
Parse the strings into real date objects so that month ends, leap days and year ends are handled by date subtraction, and update a running maximum at each step.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a "gaps and islands" problem. For each customer, the distinct purchase dates form islands of back-to-back days, and the answer is the size of the largest island.
- Walk through the records and build a mapping from
user_idto a set of dates. Converting each string to adateobject means same-day purchases collapse into one entry and date arithmetic is calendar-correct. - For each customer, in ascending
user_idorder, sort the distinct dates. - Scan the sorted dates with a running counter
current:- If the date is exactly one day after the previous date, increment
current. - Otherwise, reset
currentto 1. - Update
bestwith the maximum seen so far.
- If the date is exactly one day after the previous date, increment
- Append
[user_id, best]to the result.
Why it is correct
- After deduplication, two neighbouring sorted dates differ by at least one day. A difference of exactly one extends the streak, and anything larger is a gap that starts a new streak.
- At each date,
currentequals the length of the streak ending there, so the length of every streak is observed at its last date and the running maximum equals the largest streak. - Using real date subtraction handles month ends, leap days and year boundaries without special cases.
- Every customer that appears has at least one date, so the result is at least 1. An empty input produces an empty output.
- Iterating over
sorted(dates_by_user)guarantees the required output order.
Complexity
Let n be the number of records and d the number of distinct (customer, date) pairs.
- Time: O(n + d log d), dominated by sorting each customer's dates.
- Space: O(d) for the date sets, plus the output.
Reference solution
from datetime import date
from typing import Dict, List
def longest_purchase_streaks(orders: List[Dict[str, str]]) -> List[List[int]]:
dates_by_user = {}
for order in orders:
user_id = order["user_id"]
day = date.fromisoformat(order["order_date"])
dates_by_user.setdefault(user_id, set()).add(day)
result = []
for user_id in sorted(dates_by_user):
days = sorted(dates_by_user[user_id])
best = current = 0
previous = None
for day in days:
if previous is not None and (day - previous).days == 1:
current += 1
else:
current = 1
if current > best:
best = current
previous = day
result.append([user_id, best])
return result