LeetCode 1241: Number of Comments per Post Solution

Master LeetCode problem 1241 (Number of Comments per Post), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1241. Number of Comments per Post

Problem Explanation

Explanation

Given a list of comments where each comment contains the id of the post it belongs to, we need to find the number of comments per post. We can achieve this by iterating through the comments and maintaining a map to store the count of comments per post. Finally, we return the count of comments for each post.

  • Algorithmic Idea:

    1. Initialize a map postCommentCount to store the count of comments per post.
    2. Iterate through the comments list, updating the count of comments for each post in the map.
    3. Return the count of comments for each post as a list.
  • Time Complexity: O(N), where N is the number of comments.

  • Space Complexity: O(N), for the map to store the count of comments per post.

Solution Code

class Solution {
    public List<Integer> numOfCommentsPerPost(int[] comments) {
        Map<Integer, Integer> postCommentCount = new HashMap<>();
        for (int comment : comments) {
            postCommentCount.put(comment, postCommentCount.getOrDefault(comment, 0) + 1);
        }
        
        List<Integer> result = new ArrayList<>();
        for (int post : postCommentCount.keySet()) {
            result.add(postCommentCount.get(post));
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1241 (Number of Comments per Post)?

This page provides optimized solutions for LeetCode problem 1241 (Number of Comments per Post) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1241 (Number of Comments per Post)?

The time complexity for LeetCode 1241 (Number of Comments per Post) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1241 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1241 in Java, C++, or Python.

Back to LeetCode Solutions