Design a simplified Twitter with four operations: postTweet(userId, tweetId), follow(followerId, followeeId), unfollow(followerId, followeeId), and getNewsFeed(userId) which returns the 10 most recent tweet ids posted by the user or anyone they follow, newest first.
postTweet(1, 5); getNewsFeed(1) ⟶ [5]follow(1, 2); postTweet(2, 6); getNewsFeed(1) ⟶ 65Constraints: at most 3·10⁴ total calls; all ids in [1, 500].
You open Twitter. You scroll. Tweets from 47 accounts interleave seamlessly — newest first, regardless of who posted it. You've never wondered how.
Here's what your feed is NOT doing: it's not collecting every tweet from every account, dumping them in a pile, and re-ordering from scratch. That would work for 4 accounts. For 4,000 accounts posting 10 tweets each, it's 40,000 items touched per refresh. Your phone would melt.
Three users: A, B, C. Your job: post three tweets as A, follow B, unfollow C. Watch the global timestamp counter and the follows[A] chip change.
let timestamp = 0;const userTweets = new Map<number, { time: number, id: number }[]>();const follows = new Map<number, Set<number>>();function postTweet(userId: number, tweetId: number) { timestamp += 1; const list = userTweets.get(userId) ?? []; list.unshift({ time: timestamp, id: tweetId }); // prepend → newest at index 0 userTweets.set(userId, list);}function follow(a: number, b: number) { const set = follows.get(a) ?? new Set<number>(); set.add(b); follows.set(a, set);}function unfollow(a: number, b: number) { follows.get(a)?.delete(b);}You're about to post 3 tweets as User A. Each call is postTweet(A, tweetId) with no timestamp argument. Where does each tweet's ordering come from?