37. Sorted Distinct Purchase List
Difficulty: Medium · Topics: Arrays, Aggregations
For each customer_id in purchases, return products, the distinct products they bought as an array sorted alphabetically, and product_count, the number of distinct products.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
purchases
| customer_id | product |
|---|---|
| 1 | pear |
| 1 | apple |
| 1 | pear |
| 2 | kiwi |
Expected output
| customer_id | products | product_count |
|---|---|---|
| 1 | [apple, pear] | 2 |
| 2 | [kiwi] | 1 |
Hints
Hint 1
F.collect_set gathers distinct values per group, in no guaranteed order.Hint 2
Wrap it inF.sort_array for a deterministic, sorted array.Hint 3
F.size gives the array length.Learn the concepts
- Array functions · 4 min read. array_contains, size, element_at, sort_array and the set functions, without exploding.
- collect_list / collect_set · 4 min read. Gather the values of a group into an array, with or without duplicates, and in which order.
- groupBy + agg · 4 min read. Aggregate rows per group: counts, sums, averages, and how count(*) differs from count(col).
PySpark functions you'll practise
- groupBy
- agg
- collect_set
- sort_array
- size
- withColumn
Related problems
- Learning Path per Student · Medium · Arrays, Aggregations, Strings, Filtering & Selection
- Word Count · Medium · Arrays, Aggregations, Strings, Filtering & Selection
- Item Positions in a Basket (POSEXPLODE) · Medium · Arrays, Filtering & Selection
- Keep Users with No Interests (EXPLODE_OUTER) · Medium · Arrays, Filtering & Selection
- Conditional Aggregation · Medium · Aggregations, Conditional Logic
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice