EasyNo. 1241LeetCode Premium
Number of Comments per Post — LeetCode 1241 Python Solution
- Topics
- Database
- Reading time
- 3 min
- Source
- leetcode.com
Table 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
+---------------+----------+
| 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
- Time
- O(n log n)(typical)
- Space · auxiliary
- O(n)
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0175 | Combine Two Tables | Easy |
| 0176 | Second Highest Salary | Medium |
| 0177 | Nth Highest Salary | Medium |
| 0178 | Rank Scores | Medium |
| 0180 | Consecutive Numbers | Medium |
| 0181 | Employees Earning More Than Their Managers | Easy |
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.