44. Item Positions in a Basket (POSEXPLODE)
Difficulty: Medium · Topics: Arrays, Filtering & Selection
Each row of baskets has an order_id and items, an array in the order the items were scanned.
Return one row per item: order_id, position (1 for the first item) and item. Orders with an empty or missing basket produce no rows.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
baskets
| order_id | items |
|---|---|
| 1 | [milk, bread, eggs] |
| 2 | [tea] |
Expected output
| order_id | position | item |
|---|---|---|
| 1 | 1 | milk |
| 1 | 2 | bread |
| 1 | 3 | eggs |
| 2 | 1 | tea |
Hints
Hint 1
F.explode loses the position; F.posexplode returns it as well (0-based).Hint 2
Name both outputs:F.posexplode("items").alias("pos", "item").Hint 3
Add 1 to make positions start at 1.PySpark functions you'll practise
- posexplode
- select
Related problems
- Word Count · Medium · Arrays
- Fill Missing Dates (Calendar Spine) · Hard · Joins
- Keep Users with No Interests (EXPLODE_OUTER) · Medium · Arrays
- Filter High Earners · Easy · Filtering & Selection
- Distinct User Actions · Easy · Filtering & Selection
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