Number of Comments per Post — LeetCode 1241 Python Solution

EasyLeetCode PremiumDatabase
Problem
#1241
Reading time
3 min

Table schema

SQL
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.

Example

SQL
+---------------+----------+
| 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

Python
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

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1241. Number of Comments per Post?
LeetCode 1241. Number of Comments per Post is rated Easy on LeetCode.
What topics does LeetCode 1241. Number of Comments per Post cover?
LeetCode 1241. Number of Comments per Post is tagged Database on LeetCode.
Is LeetCode 1241. Number of Comments per Post a premium problem?
Yes. LeetCode 1241. Number of Comments per Post is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview