Group and Rank Feed Items with Photo Bundling
Heaps, Sorting & SearchAuto-graded · 18 test casesLast updated
Rearrange feed items by sorting on rank score, grouping photos into batches of up to three, and maintaining stable ordering for equal scores.
Given a list of feed elements, construct an ordered feed by applying ranking and photo-grouping rules.
Each input element is represented as a dictionary containing three keys:
"id": a string unique to the element"type": a string denoting the category ("Normal","Video", or"Photo")"score": a numerical ranking score (higher is better)
You must assemble the final output list according to the following procedure:
- Initial Ranking: Sort all items in descending order of their
"score". If two items share the same score, preserve their relative order from the input array (stable sort). - Photo Grouping: Extract all
"Photo"items from the sorted list in their established rank order and group them into consecutive chunks of size up to 3. Each chunk contains 1, 2, or 3 photo dictionaries. - Batch Scoring: A photo batch is treated as a single compound feed entry. Its ranking score is defined as the score of its first (highest-ranked) photo.
- Final Merging: Merge the photo batches back with the standalone
"Normal"and"Video"items. Order all items by score descending. Ties must be resolved using the original sorted position established in Step 1 (the index of the standalone item or the index of the first photo in a batch).
The final returned list contains the individual dictionary items for "Normal" and "Video" entries, and Python lists of photo dictionaries for photo batch entries.
Constraints
- $0 \le \text{len(items)} \le 10^5$
- Every item has valid keys
"id"(str),"type"("Normal","Video", or"Photo"), and"score"(int or float).
Examples
Example 1
Input: build_ranked_feed([{'id': 'N1', 'type': 'Normal', 'score': 100}, {'id': 'N2', 'type': 'Normal', 'score': 90}, {'id': 'P1', 'type': 'Photo', 'score': 80}, {'id': 'P2', 'type': 'Photo', 'score': 70}, {'id': 'V', 'type': 'Video', 'score': 60}, {'id': 'P3', 'type': 'Photo', 'score': 50}, {'id': 'P4', 'type': 'Photo', 'score': 40}, {'id': 'N3', 'type': 'Normal', 'score': 30}])
Output: [{'id': 'N1', 'type': 'Normal', 'score': 100}, {'id': 'N2', 'type': 'Normal', 'score': 90}, [{'id': 'P1', 'type': 'Photo', 'score': 80}, {'id': 'P2', 'type': 'Photo', 'score': 70}, {'id': 'P3', 'type': 'Photo', 'score': 50}], {'id': 'V', 'type': 'Video', 'score': 60}, [{'id': 'P4', 'type': 'Photo', 'score': 40}], {'id': 'N3', 'type': 'Normal', 'score': 30}]
Example 2
Input: build_ranked_feed([{'id': 'P1', 'type': 'Photo', 'score': 10}, {'id': 'N1', 'type': 'Normal', 'score': 10}, {'id': 'P2', 'type': 'Photo', 'score': 9}, {'id': 'P3', 'type': 'Photo', 'score': 8}, {'id': 'V1', 'type': 'Video', 'score': 8}, {'id': 'P4', 'type': 'Photo', 'score': 7}])
Output: [[{'id': 'P1', 'type': 'Photo', 'score': 10}, {'id': 'P2', 'type': 'Photo', 'score': 9}, {'id': 'P3', 'type': 'Photo', 'score': 8}], {'id': 'N1', 'type': 'Normal', 'score': 10}, {'id': 'V1', 'type': 'Video', 'score': 8}, [{'id': 'P4', 'type': 'Photo', 'score': 7}]]
Hints
Hint 1
Python's native `sort` and `sorted` are stable, meaning ties preserve insertion order naturally.
Hint 2
Collect all photos after the initial sort, slice them into sublists of size 3, and mark the starting index of each batch in the sorted order.
Hint 3
When creating candidate elements for the final list, associate each non-photo item and each photo batch anchor with its rank score and original sorted index.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires a structured approach to sorting, filtering, batching, and re-merging:
- Initial Stable Sort: Sort all input items by
-item["score"]. Because Python'ssorted()algorithm (Timsort) is stable, elements with identical scores maintain their original relative order. - Batching Photos: Iterate through the stably sorted elements, filtering out
"Photo"types while preserving their index in this ranked list. Then chunk these photos into groups of 3 using index steps of 3. Record each batch in a hash map keyed by the ranked index of its first (highest-scored) photo. - Collecting Output Candidates: Iterate through the ranked list once more:
- For non-photo entries (
"Normal"or"Video"), construct a tuple(score, ranked_index, item). - For photo entries, check if the current index is the starting anchor of a photo batch. If so, construct a candidate tuple
(first_photo_score, ranked_index, photo_batch_list). Subsequent photos within the batch are skipped since they are included inside the batch list.
- For non-photo entries (
- Final Ordering: Sort candidate tuples by primary key
-score(descending score) and secondary keyranked_index(ascending initial rank index to maintain relative order on ties). Extract and return the payload from each candidate tuple.
Complexity
- Time Complexity: $\mathcal{O}(N \log N)$ where $N$ is the number of feed elements. Sorting the initial array takes $\mathcal{O}(N \log N)$ time. Filtering, grouping, and building candidates take $\mathcal{O}(N)$ time. The second sort takes $\mathcal{O}(N \log N)$ in the general case (though Timsort runs in near $\mathcal{O}(N)$ time since the candidate list is nearly sorted).
- Space Complexity: $\mathcal{O}(N)$ space to store the intermediate ranked list, photo groups, batch map, and final output entries.
from typing import Dict, List, Any
def build_ranked_feed(items: List[Dict[str, Any]]) -> List[Any]:
# 1. Stably sort by score descending
ranked = sorted(items, key=lambda item: -item["score"])
# 2. Extract photos and chunk them into batches of 3
photos = [(idx, item) for idx, item in enumerate(ranked) if item["type"] == "Photo"]
batch_map = {}
for i in range(0, len(photos), 3):
chunk = photos[i:i + 3]
anchor_idx = chunk[0][0]
batch_map[anchor_idx] = [item for _, item in chunk]
# 3. Create candidates for the final output
candidates = []
for idx, item in enumerate(ranked):
if item["type"] == "Photo":
if idx in batch_map:
batch = batch_map[idx]
candidates.append((batch[0]["score"], idx, batch))
else:
candidates.append((item["score"], idx, item))
# 4. Sort candidates by score descending, then by initial ranked index ascending
candidates.sort(key=lambda cand: (-cand[0], cand[1]))
return [content for _, _, content in candidates]