#3497
Analyze Subscription Conversion
MediumDatabaseHash 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 single pass to aggregate activity data for each user, storing results in a hash map for efficient lookups.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through UserActivity and store total duration and counts for free trial and paid subscription in a hash map.
- 2Step 2: After processing, calculate averages using stored totals and counts.
- 3Step 3: Return results for users who converted from free trial to paid.
solution.py7 lines
1# Full working Python code
2SELECT user_id,
3 ROUND(SUM(CASE WHEN activity_type = 'free_trial' THEN activity_duration END) / COUNT(CASE WHEN activity_type = 'free_trial' THEN 1 END), 2) AS avg_free_trial,
4 ROUND(SUM(CASE WHEN activity_type = 'paid' THEN activity_duration END) / COUNT(CASE WHEN activity_type = 'paid' THEN 1 END), 2) AS avg_paid
5FROM UserActivity
6WHERE user_id IN (SELECT user_id FROM UserActivity WHERE activity_type = 'paid')
7GROUP BY user_id;ℹ
Complexity note: Single pass through data allows for linear complexity; space used for storing user data.
- 1Users who convert show different engagement patterns.
- 2Tracking activity duration can inform retention strategies.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.