Daily Spend Ranking for Frequent Payers
SQL & DataAuto-graded · 13 test casesLast updated
Filter users by total event count, then rank each user's payments within each calendar day by amount using competition ranking (ties share a rank, then a gap).
Daily Spend Ranking for Frequent Payers
A payments log is given as a list of records, one per payment. Each record is a dictionary with these keys:
user_id: an integer identifying the user.amount: a number giving the payment value.transaction_time: an ISO-8601 timestamp string such as"2023-01-01T10:00:00".
Implement a function that finds the frequent payers and ranks their payments within each day.
Task
- Select frequent payers. A user qualifies only if they have strictly more than 5 payments in the entire input, counted across all days.
- Rank within each day. For each qualifying user and each calendar day (the date part of
transaction_time), rank that user's payments for that day byamountfrom highest to lowest. The highest amount gets rank 1. - Ties use competition ranking. Payments with equal amounts on the same user and day share the same rank, and the following rank is skipped. For example, ranks come out as 1, 2, 2, 4, not 1, 2, 2, 3. Each day starts again at rank 1.
Output
Return a list of dictionaries, one for each payment belonging to a qualifying user. Each dictionary has exactly these keys:
user_idtransaction_time(the original string, unchanged)amountday_rank
Sort the returned list by user_id ascending, then transaction_time ascending, then amount descending.
If no user qualifies, return an empty list. Duplicate records (same user, time and amount) are all kept and receive the same rank.
Constraints
- The input list may be empty.
transaction_timevalues are valid ISO-8601 strings that can be parsed bydatetime.fromisoformat; the day is taken directly from the timestamp, with no time-zone conversion.- The eligibility check uses the user's total payment count over all days, not the per-day count.
- A user with exactly 5 payments does not qualify.
- Only ranks within the same user and same day are compared; payments of different users or different days never affect each other's rank.
Examples
Example 1
Input: rank_daily_payments([{'user_id': 1, 'amount': 100, 'transaction_time': '2023-01-01T10:00:00'}, {'user_id': 1, 'amount': 200, 'transaction_time': '2023-01-01T11:00:00'}, {'user_id': 1, 'amount': 100, 'transaction_time': '2023-01-01T12:00:00'}, {'user_id': 1, 'amount': 50, 'transaction_time': '2023-01-02T10:00:00'}, {'user_id': 1, 'amount': 60, 'transaction_time': '2023-01-02T11:00:00'}, {'user_id': 1, 'amount': 70, 'transaction_time': '2023-01-02T12:00:00'}])
Output: [{'user_id': 1, 'transaction_time': '2023-01-01T10:00:00', 'amount': 100, 'day_rank': 2}, {'user_id': 1, 'transaction_time': '2023-01-01T11:00:00', 'amount': 200, 'day_rank': 1}, {'user_id': 1, 'transaction_time': '2023-01-01T12:00:00', 'amount': 100, 'day_rank': 2}, {'user_id': 1, 'transaction_time': '2023-01-02T10:00:00', 'amount': 50, 'day_rank': 3}, {'user_id': 1, 'transaction_time': '2023-01-02T11:00:00', 'amount': 60, 'day_rank': 2}, {'user_id': 1, 'transaction_time': '2023-01-02T12:00:00', 'amount': 70, 'day_rank': 1}]
Hints
Hint 1
Do this in two phases: first count payments per user over the entire input to find who qualifies, then handle the ranking only for those users.
Hint 2
Group the qualifying payments by the pair (user_id, calendar date). Parse the timestamp and take its date so that different times on the same day land in the same group.
Hint 3
Sort each group by amount descending. A row's rank is its 1-based position, unless its amount equals the previous row's amount, in which case it reuses the previous rank. Finally sort the output as specified.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task has two independent parts.
- Filter by total activity. Count payments per user over the whole input and keep only users whose count is strictly greater than 5. This is the equivalent of
GROUP BY user_id HAVING COUNT(*) > 5. - Rank within each user-day. Group the remaining payments by
(user_id, date), where the date is taken from the parsed timestamp. Sort each group by amount descending and assign competition ranks: a row's rank is its 1-based position in the sorted group, except that a row whose amount equals the previous row's amount reuses the previous rank. This is what SQL'sRANK()does and it produces sequences like 1, 2, 2, 4.
Finally, sort all output rows by user_id, transaction_time, and amount descending.
Why it is correct
- Eligibility depends only on the user's total count, so a user with payments spread over many days still qualifies. Counting per day would be wrong.
- Removing ineligible users removes whole user-day groups, so it never changes the ranks inside the remaining groups.
- In a group sorted by amount descending, the rank of a row equals 1 plus the number of rows with a strictly higher amount. Position-based ranking with reuse on ties gives exactly this value, which yields the gap after tied rows.
- Grouping by calendar date means 10:00 and 23:59 on the same day are ranked together, while different days restart at rank 1.
- The secondary sort key within a group (
transaction_time) only makes the order deterministic and has no effect on the rank values.
Complexity
- Time: O(n log n), dominated by the sorting of groups and the final sort.
- Space: O(n) for the groups and the output.
Reference solution
from collections import Counter
from datetime import datetime
from typing import Dict, List
def rank_daily_payments(payments: List[Dict[str, str]]) -> List[Dict[str, object]]:
counts = Counter(row["user_id"] for row in payments)
eligible = {user_id for user_id, count in counts.items() if count > 5}
grouped = {}
for row in payments:
user_id = row["user_id"]
if user_id not in eligible:
continue
timestamp = datetime.fromisoformat(row["transaction_time"])
day = timestamp.date()
grouped.setdefault((user_id, day), []).append(row)
result = []
for rows in grouped.values():
rows.sort(key=lambda row: (-row["amount"], row["transaction_time"]))
previous_amount = None
rank = 0
for index, row in enumerate(rows, 1):
if index == 1 or row["amount"] != previous_amount:
rank = index
result.append({
"user_id": row["user_id"],
"transaction_time": row["transaction_time"],
"amount": row["amount"],
"day_rank": rank,
})
previous_amount = row["amount"]
result.sort(key=lambda row: (row["user_id"], row["transaction_time"], -row["amount"]))
return result