Skip to content

14. Find Partitions That Need Compaction

Difficulty: Easy · Topics: Aggregations, Filtering & Selection

files lists the data files of a table: partition, path and size_mb.

A partition needs compaction when it has more than 3 files and their average size is under 32 MB. Return partition, file_count and avg_mb (rounded to 1 decimal) for those partitions, with the most files first (ties by partition name).

Row order matters for this problem. Your code is graded on 3 test cases, including hidden edge cases.

Sample data

files

partitionpathsize_mb
2025-03-01a4
2025-03-01b6
2025-03-01c3
2025-03-01d5
2025-03-02e300
2025-03-02f280
2025-03-03g2
2025-03-03h2
2025-03-03i1
2025-03-03j2
2025-03-03k1

Expected output

partitionfile_countavg_mb
2025-03-0351.6
2025-03-0144.5

Hints

Hint 1Group by partition and aggregate a count and an average.
Hint 2Filter after the aggregation; that is SQL's HAVING.
Hint 3Sort by file_count descending, then partition ascending.

Learn the concepts

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 · Learn · All problems