#550
Game Play Analysis IV
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)
The optimal solution uses a single pass through the data to track first logins and check for subsequent logins, which is more efficient than the brute force method.
⚙️
Algorithm
5 steps- 1Step 1: Create a dictionary to store the first login date for each player.
- 2Step 2: Iterate through the Activity table to populate this dictionary.
- 3Step 3: Create a set to track players who logged in the day after their first login.
- 4Step 4: Iterate through the Activity table again to check if players logged in on the day after their first login date.
- 5Step 5: Calculate the fraction of players who logged in again and round to 2 decimal places.
solution.py14 lines
1# Full working Python code
2WITH FirstLogins AS (
3 SELECT player_id, MIN(event_date) AS first_login
4 FROM Activity
5 GROUP BY player_id
6), SubsequentLogins AS (
7 SELECT DISTINCT a.player_id
8 FROM Activity a
9 JOIN FirstLogins fl ON a.player_id = fl.player_id
10 WHERE a.event_date = DATE_ADD(fl.first_login, INTERVAL 1 DAY)
11)
12SELECT ROUND(COUNT(DISTINCT sl.player_id) * 1.0 / COUNT(DISTINCT fl.player_id), 2) AS fraction
13FROM FirstLogins fl
14LEFT JOIN SubsequentLogins sl ON fl.player_id = sl.player_id;ℹ
Complexity note: This complexity is due to the need to store first login dates and track subsequent logins, which requires linear space and time.
- 1Understanding how to track unique player logins is crucial for solving this problem.
- 2Using date functions effectively can simplify the logic for checking subsequent logins.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.