EasyNo. 1241LeetCode Premium

Number of Comments per Post — LeetCode 1241 Python Solution

Topics
Database
Reading time
3 min

Table schema

SQLTable schema
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

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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

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.

Free to download. Check it runs on your machine, then pick a plan.