KatInterview

Longest Daily Purchase Streak for Each Customer

Arrays & HashingAuto-graded · 14 test cases
MediumAuto-gradedArrays & Hashinghashingsortingdates

Last 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 in YYYY-MM-DD format.

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-31 followed by 2024-02-01, 2024-02-28 followed by 2024-02-29 in a leap year, and 2023-12-31 followed by 2024-01-01 are 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_streak is at least 1.
  • Return the pairs sorted by user_id in ascending order, with exactly one pair per customer.
  • If the input list is empty, return an empty list.

Constraints

  • 0 <= len(orders) <= 10^5
  • user_id is an integer.
  • order_date is always a valid date in YYYY-MM-DD format.
  • The return value is a list of [user_id, best_streak] lists, sorted by user_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.