Problem
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.
parent_id is null for posts.
parent_id for comments is sub_id for another post in the table.
Write a solution to find the number of comments per post. The result table should contain post_id
and its corresponding number_of_comments
.
The Submissions
table may contain duplicate comments. You should count the number of unique comments per post.
The Submissions
table may contain duplicate posts. You should treat them as one post.
The result table should be ordered by post_id
in ascending order.
The result format is in the following example.
Examples
Example 1:
|
|
Solution
Method 1 – SQL Group By and Join
Intuition
Posts are rows with parent_id IS NULL. Comments are rows with parent_id = sub_id of a post. Count unique comments per post, ignoring duplicates and comments on deleted posts.
Approach
- Select distinct post ids (parent_id IS NULL).
- Left join with distinct comments (parent_id = post_id).
- Count unique comment ids per post.
- Order by post_id ascending.
Code
|
|
Complexity
- ⏰ Time complexity:
O(N log N)
- 🧺 Space complexity:
O(N)