30. Entry and Exit Pages (MAX_BY / MIN_BY)
Difficulty: Medium · Topics: Aggregations
For each session_id in pageviews, find the entry_page (first page viewed), the exit_page (last page viewed) and pages (number of views).
Return session_id, entry_page, exit_page, pages. Timestamps within a session are unique.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
pageviews
| session_id | ts | page |
|---|---|---|
| s1 | 2024-01-01 10:00:00 | /home |
| s1 | 2024-01-01 10:01:00 | /pricing |
| s1 | 2024-01-01 10:05:00 | /signup |
| s2 | 2024-01-01 11:00:00 | /blog |
Expected output
| session_id | entry_page | exit_page | pages |
|---|---|---|---|
| s1 | /home | /signup | 3 |
| s2 | /blog | /blog | 1 |
Hints
Hint 1
You need "the page at the smallest timestamp", not the smallest page.Hint 2
F.min_by("page", "ts") and F.max_by("page", "ts") do exactly that inside one groupBy.Hint 3
Without them you would need a window withrow_number or a join back to the min/max timestamp.PySpark functions you'll practise
- groupBy
- agg
- count
- max_by
- min_by
Related problems
- Average Salary by Department · Easy · Aggregations
- Word Count · Medium · Arrays
- Departments with Large Teams · Easy · Aggregations
- Three-Day Login Streak · Hard · Window Functions
- Pivot with Several Aggregations · Hard · Pivot, Unpivot & Rollup
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