The Ripple Effect

20pts
Tik Tok, X, Meta

Problem Statement

When a "Root Post" is created, it can be shared by others. Those shares can then be shared again, creating a Viral Chain.

To measure the "Viral Velocity," the marketing team needs to know the Maximum Depth (how many levels deep the chain went) and the Total Reach (total number of shares) for every Root Post.

The Challenge

Find the viral metrics for every post_id that is a "Root Post" (where parent_post_id is NULL).

Rules:

  • A Root Post itself is Level 0.
  • A direct share of a Root Post is Level 1.
  • A share of a Level 1 share is Level 2, and so on.
  • Output: root_post_id, max_depth, and total_shares.
  • Order by max_depth DESC, then total_shares DESC.
Tests your understanding of
Recursion, CTE, Graph Traversal and Tree Structures

Input Tables

posts
post_id(INTEGER)parent_post_id(INTEGER)user_id(INTEGER)
1null10
2111
3112
4213
5214
6415
7616
8317
100null20
10110021
10210022
500null30

Expected Output

root_post_id(INTEGER)max_depth(INTEGER)total_shares(INTEGER)
147
10012
50000

Tags

HardRecursionCTEGraph TraversalTree Structures
35-45 min
12%