> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Design Twitter Python Solution with Tests

> Tested Python solution for LeetCode 355 with 13 pytest cases. Generate a practice environment with lcpy.

LeetCode 355, Medium. Topics: Hash Table, Linked List, Design, Heap (Priority Queue). [View on LeetCode](https://leetcode.com/problems/design-twitter/description/).

Generate this problem as a practice environment: tested reference solution, 13 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 355   # by problem number
lcpy gen -s design_twitter   # by problem name
```

## Problem

Design a simplified version of Twitter where users can post tweets, follow/unfollow another user, and is able to see the `10` most recent tweets in the user's news feed.

Implement the `Twitter` class:

* `Twitter()` Initializes your twitter object.
* `void postTweet(int userId, int tweetId)` Composes a new tweet with ID `tweetId` by the user `userId`. Each call to this function will be made with a unique `tweetId`.
* `List<Integer> getNewsFeed(int userId)` Retrieves the `10` most recent tweet IDs in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user themself. Tweets must be **ordered from most recent to least recent**.
* `void follow(int followerId, int followeeId)` The user with ID `followerId` started following the user with ID `followeeId`.
* `void unfollow(int followerId, int followeeId)` The user with ID `followerId` started unfollowing the user with ID `followeeId`.

### Examples

```
Input
["Twitter", "postTweet", "getNewsFeed", "follow", "postTweet", "getNewsFeed", "unfollow", "getNewsFeed"]
[[], [1, 5], [1], [1, 2], [2, 6], [1], [1, 2], [1]]
Output
[null, null, [5], null, null, [6, 5], null, [5]]

Explanation
Twitter twitter = new Twitter();
twitter.postTweet(1, 5); // User 1 posts a new tweet (id = 5).
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5]. return [5]
twitter.follow(1, 2);    // User 1 follows user 2.
twitter.postTweet(2, 6); // User 2 posts a new tweet (id = 6).
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 2 tweet ids -> [6, 5]. Tweet id 6 should precede tweet id 5 because it is posted after tweet id 5.
twitter.unfollow(1, 2);  // User 1 unfollows user 2.
twitter.getNewsFeed(1);  // User 1's news feed should return a list with 1 tweet id -> [5], since user 1 is no longer following user 2.
```

### Constraints

* 1 \<= userId, followerId, followeeId \<= 500
* 0 \<= tweetId \<= 10^4
* All the tweets have **unique** IDs.
* At most `3 * 10^4` calls will be made to `postTweet`, `getNewsFeed`, `follow`, and `unfollow`.
* A user cannot follow himself.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/design_twitter/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/design_twitter/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heapq


class Twitter:
    def __init__(self) -> None:
        self.tweets: dict[int, list[tuple[int, int]]] = {}
        self.following: dict[int, set[int]] = {}
        self.timestamp = 0

    # Time: O(1)
    # Space: O(1)
    def post_tweet(self, user_id: int, tweet_id: int) -> None:
        self.timestamp += 1
        self.tweets.setdefault(user_id, []).append((self.timestamp, tweet_id))

    # Time: O(F * T log(F * T)) where F = followee count, T = tweets per user (bounded by 10)
    # Space: O(F * 10)
    def get_news_feed(self, user_id: int) -> list[int]:
        followees = self.following.get(user_id, set()) | {user_id}
        heap: list[tuple[int, int]] = []
        for followee in followees:
            # Only the 10 most recent per user can ever appear in the top-10 feed
            for time, tweet_id in self.tweets.get(followee, [])[-10:]:
                heapq.heappush(heap, (time, tweet_id))
                if len(heap) > 10:
                    heapq.heappop(heap)
        heap.sort(reverse=True)
        return [tweet_id for _, tweet_id in heap]

    # Time: O(1)
    # Space: O(1)
    def follow(self, follower_id: int, followee_id: int) -> None:
        if follower_id == followee_id:
            return
        self.following.setdefault(follower_id, set()).add(followee_id)

    # Time: O(1)
    # Space: O(1)
    def unfollow(self, follower_id: int, followee_id: int) -> None:
        self.following.get(follower_id, set()).discard(followee_id)
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(1) | O(1)  |

## Tags

[NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
