Leetcode #1241: Number of Comments per Post
In this guide, we solve Leetcode #1241 Number of Comments per Post in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
Table: Submissions +---------------+----------+ | Column Name | Type | +---------------+----------+ | sub_id | int | | parent_id | int | +---------------+----------+ This table may have duplicate rows. Each row can be a post or comment on the post.
Quick Facts
- Difficulty: Easy
- Premium: Yes
- Tags: Database
Intuition
The task is relational in nature, which maps cleanly to DataFrame operations in Python.
By treating tables as DataFrames, joins and group-bys become concise and readable.
Approach
Load the inputs as DataFrames and apply the appropriate merge, filter, or group-by.
Select or rename the columns to match the required output.
Steps:
- Load inputs as DataFrames.
- Apply merge/groupby/filter operations.
- Select the output columns.
Example
+---------------+----------+
| Column Name | Type |
+---------------+----------+
| sub_id | int |
| parent_id | int |
+---------------+----------+
This table may have duplicate rows.
Each row can be a post or comment on the post.
parent_id is null for posts.
parent_id for comments is sub_id for another post in the table.
Python Solution
import duckdb
import pandas as pd
def solution(submissions: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Submissions", submissions)
return con.execute("""WITH
t AS (
SELECT DISTINCT s1.sub_id AS post_id, s2.sub_id AS sub_id
FROM
Submissions AS s1
LEFT JOIN Submissions AS s2 ON s1.sub_id = s2.parent_id
WHERE s1.parent_id IS NULL
)
SELECT post_id, COUNT(sub_id) AS number_of_comments
FROM t
GROUP BY post_id
ORDER BY post_id;""").df()
Complexity
The time complexity is O(n log n) (typical). The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.