Skip to content

50. Monthly Retention by Cohort

Difficulty: Hard · Topics: Joins, Aggregations, Dates, Null Handling, Filtering & Selection

A user's cohort is the month of their first activity in activity (user_id, day). A user is retained if they were also active in the calendar month right after their cohort month.

Return per cohort: cohort_month ('YYYY-MM'), cohort_size, retained and retention_pct (1 decimal).

Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

activity

user_idday
12024-01-05
12024-02-10
22024-01-20
32024-02-01
32024-03-15
32024-03-16
42024-02-28

Expected output

cohort_monthcohort_sizeretainedretention_pct
2024-012150
2024-022150

Hints

Hint 1Reduce activity to distinct (user, month) pairs with F.trunc("day", "month").
Hint 2Each user's cohort is the minimum month; join it back to the activity months.
Hint 3Retained users have a month equal to F.add_months(cohort, 1). Left-join the counts so cohorts with nobody retained show 0.

PySpark functions you'll practise

Related problems

Browse

Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings

Difficulty: Easy · Medium · Hard · PySpark interview roadmap · All problems