Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

550. Game Play Analysis IV

Medium38.4% Acceptance
Database
Asked by:
A
Adobe
G
GSN Games
ProblemSolutions (6)VideosCompanies (2)Notes

Problem Statement

Table: Activity

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
+--------------+---------+
(player_id, event_date) is the primary key (combination of columns with unique values) of this table.
This table shows the activity of players of some games.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.

Write a solution to report the fraction of players that logged in again on the day after the day they first logged in, rounded to 2 decimal places. In other words, you need to count the number of players that logged in for at least two consecutive days starting from their first login date, then divide that number by the total number of players.

The result format is in the following example.

Example 1:

Input: 
Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
+-----------+-----------+------------+--------------+
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-03-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-----------+------------+--------------+
Output: 
+-----------+
| fraction  |
+-----------+
| 0.33      |
+-----------+
Explanation: 
Only the player with id 1 logged back in after the first day he had logged in so the answer is 1/3 = 0.33
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
â–²455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions

Approach

In #550 Game Play Analysis IV, the goal is to compute the fraction of players who logged back into the game exactly one day after their first login. The key idea is to first determine each player’s earliest login date and then verify whether they returned the following day.

A common strategy is to use a subquery or aggregation to find the MIN(event_date) for every player_id. This represents the player's first login. Next, check if a record exists where the same player logged in on first_login + 1 day. This can be done using a self join or conditional filtering on the Activity table.

Finally, count the number of players who satisfy this condition and divide it by the total number of distinct players. SQL date functions and grouping are essential for implementing this logic efficiently. The approach mainly involves table scans and grouping operations, making it scalable for typical database workloads.

Complexity

ApproachTime ComplexitySpace Complexity
Aggregation with self join / subqueryO(n)O(p)
Window function approachO(n)O(p)

Video Solution Available

Frederik Müller

View all video solutions

Solutions (6)

Approach 1: SQL Query for Aggregation

Approach: We will utilize SQL to solve this problem by taking advantage of its aggregation and date manipulation capabilities. First, we will identify each player's first login date. Then, we'll check if there's a login entry for the subsequent day after that first login date. The final step is to calculate the fraction of players who have logged in on consecutive days, starting from their first login date.

The complexity of this SQL query is primarily determined by the table scan needed for aggregation:

  • Time Complexity: O(n), where n is the number of entries in the Activity table.
  • Space Complexity: O(1), as we are using aggregation functions without requiring extra storage proportional to the input size.
1SELECT ROUND(SUM(CASE WHEN NextDay IS NOT NULL THEN 1 ELSE 0 END) / COUNT(DISTINCT player_id), 2) AS fraction FROM (SELECT a.player_id, MIN(a.event_date) AS FirstLogin, (SELECT MIN(b.event_date) FROM Activity b WHERE b.player_id = a.player_id AND b.event_date > MIN(a.event_date)) AS NextDay FROM Activity a GROUP BY a.player_id) Sub;

Explanation

The SQL query performs the following steps:

  1. For each player, calculate the first login date using the MIN function.
  2. Create a subquery to find the next available login date after the first login date for each player.
  3. Using conditional aggregation, count players who have a non-null next day login date and calculate the fraction over the total count of unique players, rounding the result to two decimal places.

Approach 2: Data Processing with Python

Approach: This approach utilizes Python's data manipulation capabilities to process the table and calculate the required fraction. We will parse the data, identify each player's first login date, and check for subsequent day logins programmatically. Finally, we'll determine the desired fraction by counting players who have re-logged on the next day after their initial login.

The complexity for this approach is:

  • Time Complexity: O(n * log(n)) due to the sorting operation within groupby and merge operations.
  • Space Complexity: O(n) since additional DataFrames are created during processing.
1import pandas as pd
2from datetime import timedelta
3
4data 


Approach 1: Using SQL to find consecutive logins

This approach involves processing the input data in a structured manner using SQL queries to identify players who logged in on consecutive days starting from their first login date. We will use SQL window functions to handle date differences effectively and then calculate the desired fraction.

Time Complexity: O(n), where n is the number of records, as each operation scales linearly with the dataset size.
Space Complexity: O(n), as additional columns are created for processing.

PythonJavaScript
1import pandas as pd
2
3data =



Approach 2: Utilizing Date Handling with Multiple Passes

This approach involves a multi-pass strategy to handle dates and detect consecutive logins by manually checking day-by-day login activity.

Time Complexity: O(n log n) due to sorting necessary for detecting consecutive logins.
Space Complexity: O(n), where n represents distinct players and their login dates.

C++Java
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4#include <string>
5#include <sstream>
6#include <iomanip>

using namespace std;

struct Activity {
    int player_id;
    int device_id;
    string event_date;
    int games_played;
};

bool isNextDay(const string& cur, const string& next) {
    tm cur_tm = {}, next_tm = {};
    strptime(cur.c_str(), "%Y-%m-%d", &cur_tm);
    strptime(next.c_str(), "%Y-%m-%d", &next_tm);

    next_tm.tm_mday--;
    mktime(&next_tm);

    return cur_tm.tm_year == next_tm.tm_year && cur_tm.tm_mon == next_tm.tm_mon && cur_tm.tm_mday == next_tm.tm_mday;
}

string fractionConsecutiveLogins(vector<Activity> data) {
    unordered_map<int, vector<string>> playerMap;

    for (const auto& activity : data) {
        playerMap[activity.player_id].push_back(activity.event_date);
    }

    int totalConsecutive = 0;
    for (auto& pair : playerMap) {
        auto& dates = pair.second;
        sort(dates.begin(), dates.end());

        for (size_t i = 1; i < dates.size(); ++i) {
            if (isNextDay(dates[i - 1], dates[i])) {
                totalConsecutive++;
                break;
            }
        }
    }

    int totalPlayers = playerMap.size();
    double fraction = static_cast<double>(totalConsecutive) / totalPlayers;

    ostringstream out;
    out << fixed << setprecision(2) << fraction;
    return out.str();
}

int main() {
    vector<Activity> data = {
        {1, 2, "2016-03-01", 5},
        {1, 2, "2016-03-02", 6},
        {2, 3, "2017-06-25", 1},
        {3, 1, "2016-03-02", 0},
        {3, 4, "2018-07-03", 5}
    };

    cout << "Fraction: " << fractionConsecutiveLogins(data) << endl;
    return 0;
}

Video Solutions

Watch expert explanations and walkthroughs

LeetCode 550: Game Play Analysis IV [SQL]

Frederik Müller
8:3110,657 views

Asked By Companies

2 companies
A
Adobe
G
GSN Games

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Combine Two TablesEasy
Second Highest SalaryMedium
Nth Highest SalaryMedium
Rank ScoresMedium
More similar problems

Related Topics

Database

Problem Stats

Acceptance Rate38.4%
DifficultyMedium
Companies2

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Game Play Analysis IV asked in FAANG interviews?

Yes, variations of retention and cohort analysis queries like this are commonly asked in data and backend interviews at FAANG and other tech companies. They test SQL proficiency, analytical thinking, and understanding of time-based data.

What SQL concepts are used in Game Play Analysis IV?

This problem mainly uses SQL aggregation, date arithmetic, and joins or subqueries. Functions like MIN() help identify the first login, while date comparisons determine if the player returned the next day.

What is the optimal approach for Game Play Analysis IV?

The optimal approach is to first compute each player's earliest login date using an aggregation like MIN(event_date). Then check if the same player logged in again on the next day using a join or conditional filter. Finally, divide the count of such players by the total number of players to get the fraction.

What data structure or database concept is important for Game Play Analysis IV?

The key concept is relational table grouping by player_id along with date-based filtering. Efficient use of indexes on player_id and event_date can significantly improve query performance.

Previous Problem

Game Play Analysis III

Next Problem

Median Employee Salary

=
{
'player_id'
:
[
1
,
1
,
2
,
3
,
3
]
,
'device_id'
:
[
2
,
2
,
3
,
1
,
4
]
,
'event_date'
:
[
'2016-03-01'
,
'2016-03-02'
,
'2017-06-25'
,
'2016-03-02'
,
'2018-07-03'
]
,
'games_played'
:
[
5
,
6
,
1
,
0
,
5
]
}
5
df
=
pd
.
DataFrame
(
data
)
6
df
[
'event_date'
]
=
pd
.
to_datetime
(
df
[
'event_date'
]
)
7
8
# Find first login date for each player
9
first_logins
=
df
.
groupby
(
'player_id'
)
[
'event_date'
]
.
min
(
)
.
reset_index
(
)
10
first_logins
[
'next_day'
]
=
first_logins
[
'event_date'
]
+
timedelta
(
days
=
1
)
11
12
# Check if the next day login exists
13
merged
=
pd
.
merge
(
df
,
first_logins
[
[
'player_id'
,
'next_day'
]
]
,
left_on
=
[
'player_id'
,
'event_date'
]
,
right_on
=
[
'player_id'
,
'next_day'
]
,
how
=
'inner'
)
14
count_next_day_logins
=
merged
[
'player_id'
]
.
nunique
(
)
15
total_players
=
first_logins
[
'player_id'
]
.
nunique
(
)
16
17
fraction
=
round
(
count_next_day_logins
/
total_players
,
2
)
18
print
(
fraction
)

Explanation

This Python code executes the following steps:

  1. Load the data into a pandas DataFrame and convert the event_date column to a datetime object.
  2. Calculate each player's first login date, then compute the day after their first login date.
  3. Merge the original DataFrame with the next day's calculated DataFrame to find records of repeat logins on consecutive days.
  4. Calculate the fraction of players with consecutive day logins relative to the total number of players and print the result.
pd
.
DataFrame
(
{
4
'player_id'
:
[
1
,
1
,
2
,
3
,
3
]
,
5
'device_id'
:
[
2
,
2
,
3
,
1
,
4
]
,
6
'event_date'
:
[
'2016-03-01'
,
'2016-03-02'
,
'2017-06-25'
,
'2016-03-02'
,
'2018-07-03'
]
,
7
'games_played'
:
[
5
,
6
,
1
,
0
,
5
]
8
}
)
9
data
[
'event_date'
]
=
pd
.
to_datetime
(
data
[
'event_date'
]
)
10
11
first_login
=
data
.
groupby
(
'player_id'
)
[
'event_date'
]
.
min
(
)
.
reset_index
(
)
12
first_login
.
columns
=
[
'player_id'
,
'first_login_date'
]
13
14
merged_data
=
pd
.
merge
(
data
,
first_login
,
on
=
'player_id'
)
15
merged_data
[
'next_day_login'
]
=
merged_data
[
'event_date'
]
==
(
merged_data
[
'first_login_date'
]
+
pd
.
Timedelta
(
days
=
1
)
)
16
17
consecutive_login_players
=
merged_data
.
groupby
(
'player_id'
)
[
'next_day_login'
]
.
max
(
)
.
sum
(
)
18
total_players
=
first_login
[
'player_id'
]
.
nunique
(
)
19
fraction
=
consecutive_login_players
/
total_players
20
21
fraction
=
round
(
fraction
,
2
)
22
print
(
{
'fraction'
:
fraction
}
)

Explanation

This solution leverages the Pandas library to mimic SQL-like operations. First, we calculate the first login date for each player using the 'groupby' and 'min' functions. We then merge this information back into the original data to allow comparison with the subsequent login dates. By checking if the event date matches the first login date plus one day, we determine the consecutive logins. Summing and dividing provides the result fraction.

7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67

Explanation

This C++ solution uses common library functions to handle date operations while grouping data by players. It sorts the dates for each player and checks for consecutive days. The solution counts how many players meet the consecutive login criterion, resulting in the calculated fraction.