Skip to content

31. Year-over-Year Growth

Difficulty: Medium · Topics: Joins, Filtering & Selection

monthly_revenue has one row per (year, month). For every row, add prev_year_revenue (same month, previous calendar year) and yoy_pct = growth in percent, rounded to 1 decimal.

If there is no row for the same month last year, both are null. Note: some years are missing entirely. Return year, month, revenue, prev_year_revenue, yoy_pct.

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

Sample data

monthly_revenue

yearmonthrevenue
20221100
2022280
20231150
2023260

Expected output

yearmonthrevenueprev_year_revenueyoy_pct
20221100nullnull
2022280nullnull
2023115010050
202326080-25

Hints

Hint 1lag over partitionBy("month").orderBy("year") returns the previous available year, which is wrong when a year is missing.
Hint 2Instead shift the table by one year (year + 1) and join it back on (year, month).
Hint 3A left join keeps rows that have no previous year.

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