Python coding

Feed of the newest posts

Write a class Feed for a small social app; Feed(k) sets how many posts a feed shows.

  • post(user, post_id): user publishes the post post_id.
  • follow(follower, followee): follower starts following followee.
  • unfollow(follower, followee): follower stops following followee.
  • latest(user) returns the ids of the k most recent posts written by user or by anyone user follows right now, newest first (fewer if there are fewer).

Users and post ids are integers, and post ids are unique. Following twice, unfollowing someone you don't follow, and following or unfollowing yourself change nothing: you always see your own posts. post, follow and unfollow must be O(1), and the cost of latest must not grow with how many posts those users have written.

The tests call the provided run_feed(k, ops): it builds the feed, applies each operation in order and returns the list of results (None for operations that return nothing, shown as null).

Besides the tests, one large input (10,000 posts, 3,000 feed reads) with a ~500 ms limit (scaled to your device's speed): brute force won't pass.

  • run_feed(3, [["post",1,101],["post",2,201],["post",1,102],["latest",1],["follow",1,2],["latest",1],["latest",2]]) → [null,null,null,[102,101],null,[102,201,101],[201]]
  • run_feed(2, [["post",1,5],["follow",2,1],["post",2,6],["post",1,7],["latest",2],["unfollow",2,1],["latest",2]]) → [null,null,null,null,[7,6],null,[6]]
  • run_feed(2, [["post",1,8],["follow",1,1],["latest",1],["unfollow",1,1],["latest",1]]) → [null,null,[8],null,[8]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Stamp each post with a global counter and append it to its author's list: every list is then sorted by time for free, and posts of different authors compare.

Hint 2

Only an author's last k posts can ever reach a feed. Collect those from each author user sees, at most f·k candidates for f followed users, and keep the k newest.

Hint 3

Sorting every post of every followed user on each call is correct but grows with their whole history. Add the user to the authors at query time, not to their follow set.

Solution and why it works
pythonO(1) per post, follow and unfollow; O(f·k log(f·k)) per latest, f = users followed · O(posts + follows)
# --- your code ---
from collections import defaultdict
from itertools import count


class Feed:
    def __init__(self, k: int):
        self.k = k
        self.clock = count()                 # one global order for every post
        self.posts = defaultdict(list)       # user -> [(time, post_id)], oldest first
        self.following = defaultdict(set)    # user -> users they follow

    def post(self, user: int, post_id: int) -> None:
        self.posts[user].append((next(self.clock), post_id))

    def follow(self, follower: int, followee: int) -> None:
        self.following[follower].add(followee)

    def unfollow(self, follower: int, followee: int) -> None:
        self.following[follower].discard(followee)

    def latest(self, user: int) -> list[int]:
        authors = self.following[user] | {user}      # you always see your own posts
        recent = [p for a in authors for p in self.posts[a][-self.k:]]   # only these can make it
        recent.sort(reverse=True)                    # newest first, by stamp
        return [post_id for _, post_id in recent[:self.k]]


# --- provided: do not edit ---
def run_feed(k: int, ops: list[list]) -> list:
    feed = Feed(k)
    return [getattr(feed, name)(*args) for name, *args in ops]

Two hash maps hold the state: user → posts in time order, user → people followed. A global counter stamps each post, so posts of different authors compare. Only an author's last k posts can reach a feed, so sorting those f·k candidates costs O(f·k log(f·k)) however long the histories are; with many followees, a heap merge (heapq.merge) gets O(f + k log f). The traps: sorting every followed post on each call, and storing the user in their own follow set, where an unfollow hides their posts.