Collapse Image Bursts and Rank a Content Stream
Arrays & HashingAuto-graded · 13 test casesLast updated
Tests the ability to merge consecutive same-user image posts into gallery items and then apply a stable descending-timestamp sort to the resulting stream.
Problem Statement
A content-sharing platform displays a stream of posts to its users. When someone uploads several images back-to-back, showing each one as a separate card makes the stream feel overwhelming. To keep things readable, the platform merges any run of consecutive image posts from the same author into a single gallery card before the stream is sent to the client.
You receive the raw list of posts in the order they were ingested. Every post is a dictionary with these fields:
id(str): A unique identifier for this post.user_id(str): The identifier of the author.type(str): Either"photo"or"text".timestamp(int): Unix epoch time in seconds.content(str): The body text or the image URL.
What You Must Do
Step 1 — Merge image bursts.
Walk through the ingested list from left to right. Whenever you encounter two or more consecutive posts that are all of type "photo" and all share the same user_id, replace that entire run with one new gallery item:
id:"album_"followed by theidof the first post in the run.user_id: the shared author.type:"album".timestamp: the maximumtimestampfound anywhere in the run.photos: a list of thecontentvalues (image URLs) for every post in the run, kept in their original relative order.
A lone image post that is not adjacent to another image post by the same author must not be wrapped in a gallery — leave it exactly as it was (still a "photo" item with its own content field).
Any "text" post is always passed through unchanged, and it breaks a run: two image posts by the same user with a text post between them are not consecutive and therefore not merged.
Step 2 — Sort the merged stream.
Sort all items produced by Step 1 in descending order of timestamp. When two items carry the same timestamp, preserve the relative order they had after Step 1 (stable sort).
Return the final sorted list.
Constraints
0 <= len(items) <= 100,0000 <= timestamp <= 2 × 10⁹user_id,id, andcontentare non-empty strings.typeis always"photo"or"text".
Examples
Example 1
Input: process_post_stream([{'id': 'p1', 'user_id': 'alice', 'type': 'photo', 'timestamp': 100, 'content': 'url1.jpg'}, {'id': 'p2', 'user_id': 'alice', 'type': 'photo', 'timestamp': 105, 'content': 'url2.jpg'}, {'id': 't1', 'user_id': 'bob', 'type': 'text', 'timestamp': 110, 'content': 'Hello neighbors!'}, {'id': 'p3', 'user_id': 'alice', 'type': 'photo', 'timestamp': 95, 'content': 'url3.jpg'}])
Output: [{'id': 't1', 'user_id': 'bob', 'type': 'text', 'timestamp': 110, 'content': 'Hello neighbors!'}, {'id': 'album_p1', 'user_id': 'alice', 'type': 'album', 'timestamp': 105, 'photos': ['url1.jpg', 'url2.jpg']}, {'id': 'p3', 'user_id': 'alice', 'type': 'photo', 'timestamp': 95, 'content': 'url3.jpg'}]
Hints
Hint 1
Scan the list with an index variable. When you land on a photo, advance a second pointer forward for as long as the next item is also a photo by the same author. That contiguous slice is your complete burst — decide in one step whether it becomes a gallery or stays a lone photo.
Hint 2
A single photo between two text posts (or at the edge of the list) must not become a gallery. The only trigger for merging is a run of two or more consecutive same-author photos with nothing else in between.
Hint 3
Python's built-in sort is stable, so sorting by a negated timestamp key will put the highest timestamps first while naturally keeping tied items in their Step-1 order. You do not need to add a secondary tie-break key.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution has two sequential phases that are cleanly independent of each other.
Phase 1: Identify and merge image bursts
Walk the list with an index i. At each position:
- If the current item is a text post, copy it to the output as-is and advance
iby one. - If the current item is a photo, launch a second pointer
jstarting just ahead ofi. Advancejfor as long asitems[j]is also a photo by the same author. Whenjstops, the sliceitems[i:j]is the complete maximal run.- Run length ≥ 2 → emit a gallery item with
id = "album_" + items[i]["id"],timestamp = max(...)over the run, andphotosequal to the URL list in order. - Run length = 1 → emit the lone photo unchanged.
- Either way, jump
i = jso the next iteration starts right after the run.
- Run length ≥ 2 → emit a gallery item with
Every input item is visited exactly once across both pointers, giving O(n) time for this phase.
Phase 2: Stable descending sort
Python's sorted uses Timsort, which is guaranteed stable: items with equal keys keep their relative order from the input sequence. Sorting with key=lambda x: -x["timestamp"] puts the highest timestamps first. Items that tie on timestamp retain their Phase-1 order, which is what the problem requires — no secondary key is needed.
Why the logic is correct
- Runs are maximal: the inner pointer stops the moment the user changes or the type changes, so no eligible photo is left out and no ineligible one is pulled in.
- Runs never overlap: setting
i = jensures every item feeds into exactly one output entry. - A text post between two photos from the same author breaks the run because the inner loop's condition requires
type == "photo". - The album timestamp is the maximum across the run, not the first or last, because photo timestamps within a burst need not be ordered.
- Input is never mutated: lone photos and text posts are copied with
dict(item); gallery items are newly constructed dicts.
Edge cases
- Empty list → returns
[]. - Every post is a photo by the same author → one gallery item.
- Consecutive photos by alternating authors → no merges (user check fails at every step).
- A single photo surrounded by text posts → stays a
"photo"with itscontentfield intact. - Non-monotonic timestamps within a run (e.g., 100, 90, 110) → album gets timestamp 110.
- Two items with equal timestamps after merging → stable sort preserves their Phase-1 order.
Complexity
- Time: O(n log n) — the grouping pass is O(n); sorting m ≤ n items is O(m log m).
- Space: O(n) — for the merged list and the sorted output.
Reference solution
from typing import Dict, List
def process_post_stream(items: List[Dict]) -> List[Dict]:
merged = []
i = 0
while i < len(items):
item = items[i]
if item["type"] == "photo":
# Extend the run as far as consecutive same-author photos go.
j = i + 1
while (j < len(items)
and items[j]["type"] == "photo"
and items[j]["user_id"] == item["user_id"]):
j += 1
if j - i > 1:
# Two or more photos in a row — build a gallery item.
run = items[i:j]
merged.append({
"id": "album_" + item["id"],
"user_id": item["user_id"],
"type": "album",
"timestamp": max(p["timestamp"] for p in run),
"photos": [p["content"] for p in run],
})
else:
# Lone photo — pass through unchanged.
merged.append(dict(item))
i = j
else:
# Text post — pass through unchanged.
merged.append(dict(item))
i += 1
# Stable descending sort: negate timestamp so higher values sort first.
return sorted(merged, key=lambda x: -x["timestamp"])