Optimize Average Rating Calculation for Products

PYSPARK coding challenge · Difficulty: medium · Topic: PySpark SQL Optimisation · +100 XP

Problem

For each product in product_ratings, compute:

Only include products with at least 3 reviews.

Sort by avg_rating DESC, then product_id ASC.

Example Input - `product_ratings`

| review_id | product_id | rating | review_date |
| --- | --- | --- | --- |
| 1 | 281 | 5.0 | 2024-01-10 |
| 2 | 281 | 4.0 | 2024-02-15 |
| 3 | 281 | 3.0 | 2024-03-20 |
| 4 | 282 | 5.0 | 2024-01-05 |
| 5 | 282 | 5.0 | 2024-02-10 |
| 6 | 282 | 4.0 | 2024-03-15 |
| 7 | 283 | 2.0 | 2024-01-20 |
| 8 | 283 | 3.0 | 2024-02-25 |

Expected Output

| product_id | avg_rating | review_count | latest_review |
| --- | --- | --- | --- |
| 282 | 4.67 | 3 | 2024-03-15 |
| 281 | 4.0 | 3 | 2024-03-20 |

Notes

What this PYSPARK challenge teaches you

“Optimize Average Rating Calculation for Products” is a medium-level PYSPARK challenge focused on PySpark SQL Optimisation. Working through it gives you hands-on practice with groupBy, aggregate, optimization — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. Your result should return: product_id, avg_rating,.
  2. Compare your output to the Expected Output — the columns, values and row order must match exactly.

Where this comes up

Variations of this problem have been reported in interviews at Amazon, Myntra, Nykaa. Interviewers use it to check whether you can express the logic cleanly and reason about correctness on edge cases such as ties, nulls and empty groups.

How to practise it on PySpark.in

Open the challenge, write your PySpark code in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related PYSPARK challenges

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The PYSPARK environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated medium and covers PySpark SQL Optimisation.

Solve this challenge free on PySpark.in