Rank Companion Items by Shared Collections
Arrays & HashingAuto-graded · 19 test casesLast updated
Count how often each item shares a collection with a target item, then rank by count descending and name ascending, with an optional cap on the result length.
You are given a mapping from collection names to the items they contain, plus one target item. Find every other item that appears in at least one collection together with the target, and rank those items by how often they co-occur with it.
Task
Implement a function that takes:
collections: a dictionary whose keys are collection names (strings) and whose values are lists of item names (strings).target_item: a string, the item to compare against.limit: an optional integer,Noneby default.
Scoring
Process each collection independently:
- A collection is relevant if its list contains
target_item. Collections that do not contain it contribute nothing. - For every relevant collection, go through its list and add 1 to the score of each entry that is not equal to
target_item. Scores are accumulated per list entry. Inputs normally list each item at most once per collection, in which case an item gains at most 1 per collection. - An item's final score is the total accumulated over all relevant collections.
Items whose score is 0 (never seen in a relevant collection) are not in the output. target_item itself is never in the output.
Ordering
Sort the [item, score] pairs by:
- score, highest first;
- item name, ascending, for equal scores. Names are compared as plain Python strings (code point order, so uppercase letters sort before lowercase letters, and
"p10"sorts before"p2").
Applying limit
- If
limitisNone, return the full sorted list. - Otherwise, return the first
limitpairs of the sorted list, exactly as the Python slicesorted_result[:limit]would.limit = 0returns an empty list. It does not mean "no limit".- A
limitlarger than the number of qualifying items returns all of them. - A negative
limitfollows Python slice semantics, so-1drops the last pair.
Output
Return a list of two-element lists [item, score], where item is a string and score is an integer. Return [] if no qualifying items exist, for example when the target appears in no collection, appears only in collections alone, or collections is empty.
Constraints
- Collection names and item names are strings.
limitisNoneor an integer.- The input fits in memory; a single pass over all collections is sufficient.
Examples
Example 1
Input: rank_companion_items({'b1': ['a', 'c', 'd', 'e'], 'b2': ['a', 'c', 'e', 'f'], 'b3': ['a', 'c', 'g', 'i']}, 'a')
Output: [['c', 3], ['e', 2], ['d', 1], ['f', 1], ['g', 1], ['i', 1]]
Example 2
Input: rank_companion_items({'b1': ['a', 'c', 'd', 'e'], 'b2': ['a', 'c', 'e', 'f'], 'b3': ['a', 'c', 'g', 'i']}, 'a', 3)
Output: [['c', 3], ['e', 2], ['d', 1]]
Example 3
Input: rank_companion_items({'board_1': ['p1', 'p2'], 'board_2': ['p2', 'p3'], 'board_3': ['p1', 'p3', 'p4'], 'board_4': ['p1', 'p2', 'p4']}, 'p1', None)
Output: [['p2', 2], ['p4', 2], ['p3', 1]]
Hints
Hint 1
Only collections that contain the target item can contribute to any score, so skip all the others.
Hint 2
Keep a dictionary from item to running count. For each relevant collection, add 1 for every entry except the target itself.
Hint 3
Convert the dictionary into [item, score] pairs, sort with a key of (negative score, item name), then slice with result[:limit] only if limit is not None (limit 0 gives an empty list).
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A score counts the collections in which both the target and another item appear. So:
- Walk through every collection.
- If the collection does not contain the target item, ignore it, since it cannot add to any score.
- Otherwise, add 1 to the counter of every entry that is not the target.
- Turn the counters into
[item, score]pairs and sort by score descending, then item name ascending. - If
limitis notNone, slice the sorted list with[:limit].
Why it is correct
Each relevant collection adds exactly 1 to an item's counter per listing of that item, which for unique lists means 1 per collection holding both the item and the target. Items that never share a collection with the target never get a counter, so zero scores are excluded automatically, and the target is skipped explicitly. The sort key (-score, name) gives the required ordering, and slicing after sorting yields the top entries. limit = 0 yields an empty list because the slice is empty, and only None disables the cap.
Complexity
- Time: O(P + k log k), where P is the total number of list entries across all collections (the
intest on a list is linear in that list's length, which is at most the same order as iterating it) and k is the number of items with a nonzero score. - Space: O(k) for the counters and result.
Reference solution
from typing import Dict, List, Optional
def rank_companion_items(collections: Dict[str, List[str]], target_item: str, limit: Optional[int] = None) -> List[List[str]]:
scores = {}
for items in collections.values():
if target_item not in items:
continue
for item in items:
if item != target_item:
scores[item] = scores.get(item, 0) + 1
result = [[item, score] for item, score in scores.items()]
result.sort(key=lambda pair: (-pair[1], pair[0]))
if limit is not None:
result = result[:limit]
return result