Mean Distinct Item Count Per Group
Arrays & HashingAuto-graded · 18 test casesLast 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
Nonevalues when counting distinct items - Groups with empty lists or
Noneas 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
Noneor 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.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires computing a per-group metric and then averaging across all groups. The key insights are:
-
Distinctness is per-group: Each group's distinct count is computed independently. Items appearing in multiple groups count toward each group's total.
-
Handle missing data carefully: Groups with
Noneor empty lists contribute zero to the sum but must still be counted in the denominator. -
Memory-efficient processing: Build and discard each group's set one at a time rather than keeping all sets in memory simultaneously.
The algorithm iterates through each group once:
- Normalize
Nonevalues to empty lists usingitems or [] - Filter out
Noneelements and build a set of the remaining items - Add the set's size to a running total
- After processing all groups, divide the total by the number of groups and round to two decimals
Why It Works
A Python set automatically deduplicates elements, so len(set(filtered_items)) gives exactly the count of distinct non-None items for that group. By accumulating these counts and dividing by the total number of groups, we get the arithmetic mean. The empty dictionary case is handled explicitly to avoid division by zero.
Complexity
Time: O(N) where N is the total number of items across all groups. Each item is examined once to check for None and inserted into a set (amortized O(1) per item).
Space: O(K) where K is the maximum number of distinct items in any single group. Only one group's set exists at a time, and it's discarded before processing the next group. This is at most O(U) where U is the total number of unique items observed, satisfying the constraint.
Edge Cases
- Empty dictionary returns
0.0 - Groups with empty or
Nonelists count as groups with 0 distinct items Nonevalues within lists are filtered out before counting- Items shared across groups count separately for each group
- Proper rounding to two decimal places (e.g., 0.666... becomes 0.67)
from typing import Dict, List, Optional
def mean_distinct_per_group(group_items: Dict[str, Optional[List[Optional[int]]]]) -> float:
if not group_items:
return 0.0
total_distinct = 0
for items in group_items.values():
distinct_items = {item for item in (items or []) if item is not None}
total_distinct += len(distinct_items)
return round(total_distinct / len(group_items), 2)