#3832
Find Users with Persistent Behavior Patterns
HardHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a sliding window approach to efficiently find sequences of consecutive days with the same action.
⚙️
Algorithm
3 steps- 1Step 1: Sort the activity records by user_id and action_date.
- 2Step 2: Iterate through the sorted records, counting consecutive days with the same action.
- 3Step 3: If the count reaches 5, store the user and length; reset if the action changes.
solution.py10 lines
1WITH ranked AS (
2 SELECT user_id, action, action_date,
3 ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY action_date) AS rn
4 FROM activity
5)
6SELECT user_id, COUNT(*) AS streak_length
7FROM ranked
8GROUP BY user_id, action
9HAVING COUNT(*) >= 5
10ORDER BY streak_length DESC, user_id ASC;ℹ
Complexity note: The algorithm processes each record once, making it linear in complexity.
- 1Consecutive days can be tracked using a sliding window.
- 2Sorting helps in grouping actions efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.