KatInterview

Mean Distinct Item Count Per Group

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashinghash-mapsetaggregation

Last updated

Tests ability to deduplicate items within groups, handle null values, and compute aggregated metrics with proper rounding.

You are given a dictionary mapping group identifiers to lists of item IDs. Each group may contain duplicate item IDs and None values.

Write a function that computes the average number of distinct non-None item IDs per group, rounded to two decimal places.

Requirements:

  • Count distinct items separately for each group (uniqueness is per-group, not global)
  • Ignore None values when counting distinct items
  • Groups with empty lists or None as their value contribute 0 distinct items but are still included in the average calculation
  • If the input dictionary is empty, return 0.0
  • Return the result as a float rounded to exactly two decimal places

Constraints:

  • 0 ≤ number of groups ≤ 10⁵
  • 0 ≤ items per group ≤ 10⁴
  • Item IDs are integers or None
  • Group values may be None or empty lists
  • Solution should run in O(N) time where N is the total number of items across all groups
  • Space complexity should be O(K) where K is the maximum number of distinct items in any single group

Examples

Example 1

Input: mean_distinct_per_group({})

Output: 0

Example 2

Input: mean_distinct_per_group({'user1': [], 'user2': []})

Output: 0

Example 3

Input: mean_distinct_per_group({'user1': [1, 2, 2], 'user2': [1, 2, 3]})

Output: 2.5

Example 4

Input: mean_distinct_per_group({'alice': [1, 1, 2, None], 'bob': [2, 3, None], 'carol': [3, 4, 4]})

Output: 2

Hints

Hint 1

Compute distinct counts independently for each group before averaging—don't build a global set of all items.

Hint 2

A group mapped to None or an empty list still counts as one group in the denominator.

Hint 3

Use a set to track distinct items per group, then discard it before processing the next group to minimize memory usage.