Group and Rank Users by Average Value
Arrays & HashingAuto-graded · 14 test casesLast updated
Tests efficient grouping and aggregation over dictionaries, plus multi-key sorting to produce ordered output.
You are given a list of event records, where each record is a dictionary representing an action taken by a user. Each dictionary contains at least these keys:
"user_id": an identifier (integer or string)"value": a numeric measurement associated with the event
Your task is to compute the mean of all value fields for each user, then return a dictionary where:
- Keys are user IDs converted to strings
- Values are the computed means (floats)
- The dictionary maintains insertion order such that entries appear sorted by mean in descending order
- Ties (users with identical means) are broken by user ID in ascending lexicographic order when compared as strings
Important: The output dictionary should iterate in descending order by mean value. However, when comparing the test output, key-value pairs are compared as sets (order-independent). The ordering requirement ensures deterministic iteration but does not affect equality testing.
Constraints:
- 0 ≤ number of events ≤ 10⁵
- Each event dictionary is well-formed with
"user_id"and"value"keys - User IDs may appear as integers or strings in the input; treat them as equivalent after string conversion
- Values are numeric (int or float) and may be negative, zero, or positive
- If the input list is empty, return an empty dictionary
Examples
Example 1
Input: user_mean_values([{'id': 1, 'user_id': 42, 'event_type': 'click', 'value': 3.5, 'timestamp': '2024-03-10 10:00:00'}, {'id': 2, 'user_id': 17, 'event_type': 'view', 'value': 1, 'timestamp': '2024-03-10 10:01:05'}, {'id': 3, 'user_id': 42, 'event_type': 'purchase', 'value': 7, 'timestamp': '2024-03-10 10:02:30'}, {'id': 4, 'user_id': 99, 'event_type': 'click', 'value': 2.3, 'timestamp': '2024-03-10 10:04:11'}, {'id': 5, 'user_id': 17, 'event_type': 'purchase', 'value': 4.7, 'timestamp': '2024-03-10 10:05:45'}])
Output: {'17': 2.85, '42': 5.25, '99': 2.3}
Hints
Hint 1
Use running sums and counts instead of collecting all values per user to save memory and compute the mean in one pass.
Hint 2
defaultdict from collections lets you accumulate without checking if a key exists first.
Hint 3
Sort by a tuple key: (-mean, user_id_str) to get descending means with ascending ID tiebreaks, then construct the dict from the sorted pairs.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core insight is to compute means using running totals instead of storing every value. For each user, maintain two running counters: the sum of all their values and the count of their events. After processing all events in a single pass, divide sum by count for each user to get the mean.
Once means are computed, construct a list of (user_id, mean) tuples and sort by two criteria: mean descending (hence the negative sign), then user ID ascending for deterministic tie-breaking. Since Python 3.7+ guarantees dictionary insertion order, building a dict from this sorted list produces the required output format.
Why It Works
- Single-pass aggregation: Each event increments exactly one user's total and count, so after the loop completes,
totals[u] / counts[u]equals the arithmetic mean for useru - No division by zero: A user only appears in
totalsif at least one event was processed for them, guaranteeingcounts[u] ≥ 1 - Normalized keys: Converting all user IDs to strings merges events with IDs like
42and"42"under a single key, matching the return type - Correct ordering: Sorting by
(-mean, user_id)orders entries by descending mean, with string comparison of IDs resolving ties; constructing the dict from this sorted sequence preserves the order
Complexity
- Time: O(n + u log u), where n is the number of events and u is the number of distinct users. The aggregation pass takes O(n) with average O(1) dictionary operations. Sorting the u users costs O(u log u). Since u ≤ n, the worst case is O(n log n).
- Space: O(u) for the two aggregation dictionaries, the sorted list of tuples, and the output dictionary.
This approach avoids storing all values per user in lists, which would require O(n) extra space.
from collections import defaultdict
from typing import Dict, List
def user_mean_values(events: List[Dict]) -> Dict[str, float]:
totals = defaultdict(float)
counts = defaultdict(int)
for event in events:
user_id = str(event["user_id"])
totals[user_id] += event["value"]
counts[user_id] += 1
averages = [(user_id, totals[user_id] / counts[user_id]) for user_id in totals]
averages.sort(key=lambda item: (-item[1], item[0]))
return dict(averages)