Imagine you're building a user activity dashboard that tracks what your users have been up to lately. You have a database table called UserActivity that logs every activity a user performs along with start and end dates.
Your mission: Find the second most recent activity for each user. But here's the catch - if a user only has one activity on record, that single activity should be returned instead.
Think of it like looking at someone's recent history - you want to see what they did before their most recent action, but if they're a new user with only one activity, that's all you can show.
Table Structure:
| Column Name | Type |
|---|---|
| username | varchar |
| activity | varchar |
| startDate | Date |
| endDate | Date |
Key Rules:
- Users cannot perform multiple activities simultaneously
- The table may contain duplicate rows
- Return results in any order
- For users with only 1 activity, return that activity
- For users with 2+ activities, return the second most recent
Input & Output
Visualization
Time & Space Complexity
Single table scan with sorting for ROW_NUMBER() window function
Database needs to store temporary results for window function calculations
Constraints
- 1 โค Number of rows โค 104
- username contains only lowercase letters and numbers
- activity is a non-empty string
- startDate โค endDate for all rows
- Users cannot have overlapping activities (no simultaneous activities)