Design#Facebook

159
Dec 15, 2023
Dec 15, 2023
// Design Facebook
class Facebook {
  private class Post {
    private int id;
    private String content;

    public Post(int id, String post) {
      this.id = id;
      this.content = post;
    }
  }

  Map<Integer, Set<Integer>> userWithFriends;
  Map<Integer, LinkedList<Post>> userWithPost;
  int id;

  public Facebook() {
    this.userWithFriends = new HashMap<>();
    this.userWithPost = new HashMap<>();
    this.id = 1;
  }

  // Time: O(1).
  // Space: O(P + U), P is the total number of posts and U is the number of unique users who have written posts.
  public void writePost(int userId, String postContent) {
    userWithPost
        .computeIfAbsent(userId, k -> new LinkedList<>())
        .addFirst(new Post(id++, postContent));
  }

  // Time:O(K), K is the maximum number of friends between user1 and user2.
  // Space:O(F + 2 * E), F is the total number of friendships, and E is the number of unique users involved in friendships.
  public void addFriend(int user1, int user2) {
    userWithFriends.computeIfAbsent(user1, k -> new HashSet<>());
    userWithFriends.get(user1).add(user2);

    userWithFriends.computeIfAbsent(user2, k -> new HashSet<>());
    userWithFriends.get(user2).add(user1);
  }

  // Time: O(K + N * log N), K is the number of friends of userId, and N is the
  // total number of posts from all friends.
  // Space:O(N).
  public List<String> showPosts(int userId) {
    var users = userWithFriends.get(userId);
    if (Objects.isNull(users)) {
      return new ArrayList<>();
    }

    PriorityQueue<Post> queue = new PriorityQueue<>((a, b) -> b.id - a.id);
    List<String> result = new ArrayList<>();
    for (Integer user : users) {
      List<Post> posts = userWithPost.get(user);
      if (Objects.isNull(posts)) {
        continue;
      }
      for (Post post : posts) {
        queue.offer(post);
      }
    }
    while (!queue.isEmpty()) {
      Post currPost = queue.remove();
      result.add(currPost.content);
    }
    return result;
  }

  public static void main(String[] args) {
    Facebook facebook = new Facebook();
	
    facebook.addFriend(1, 2);
    facebook.writePost(1, "postone");
    facebook.writePost(2, "posttwo");
    facebook.writePost(3, "postthree");
    facebook.writePost(2, "postfour");

    System.out.println("Posts for user 2: " + facebook.showPosts(2));
    System.out.println("Posts for user 3: " + facebook.showPosts(3));
    System.out.println("Posts for user 1: " + facebook.showPosts(1));
    System.out.println("Posts for user 2: " + facebook.showPosts(2));
    System.out.println("Posts for user 3: " + facebook.showPosts(3));
  }
}
Comments (0)