KatInterview

Group and Rank Users by Average Value

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

Last 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.