47. Three-Day Login Streak
Difficulty: Hard · Topics: Window Functions, Aggregations, Dates, Filtering & Selection
logins records each day a user logged in (user_id, login_date as YYYY-MM-DD). A user may log in several times on the same day.
Return the user_id of every user who logged in on at least 3 consecutive days at some point. Each user should appear once.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
logins
| user_id | login_date |
|---|---|
| 1 | 2024-01-01 |
| 1 | 2024-01-02 |
| 1 | 2024-01-03 |
| 1 | 2024-01-05 |
| 2 | 2024-01-01 |
| 2 | 2024-01-03 |
| 2 | 2024-01-05 |
| 3 | 2024-01-10 |
| 3 | 2024-01-10 |
| 3 | 2024-01-11 |
| 3 | 2024-01-12 |
| 3 | 2024-01-12 |
Expected output
| user_id |
|---|
| 1 |
| 3 |
Hints
Hint 1
De-duplicate(user_id, login_date) first, so repeat logins on a day don't distort the numbering.Hint 2
Number each user's dates withrow_number() ordered by login_date.Hint 3
F.date_sub(login_date, rn) yields the same value for every date in an unbroken run — that value identifies the streak.Hint 4
Group by(user_id, grp), count the days, keep counts >= 3.Learn the concepts
- Gaps and islands · 7 min read. Streaks, sessions and status runs: one window pattern behind many interview questions.
- row_number / rank · 4 min read. Number and rank rows inside a window, and how the three ranking functions treat ties.
- dropDuplicates · 5 min read. Remove duplicate rows or keys, and why "keep the latest row" needs a window instead.
PySpark functions you'll practise
- Row Number
- Window spec
- groupBy
- agg
- count
- date_sub
- filter
- select
- withColumn
- orderBy
- distinct
- dropDuplicates
Related problems
- Consecutive Status Runs (Gaps and Islands) · Hard · Window Functions, Aggregations
- Build an SCD Type 2 History · Hard · Window Functions, Null Handling, Filtering & Selection
- Upsert: Merge New Records into a Table · Hard · Window Functions, Filtering & Selection
- Trailing 3 Calendar Days (Range Frame) · Hard · Window Functions, Dates, Filtering & Selection
- Sessionize a Clickstream · Hard · Window Functions, Dates, Null Handling, Conditional Logic, Filtering & Selection
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