Game Play Analysis II — LeetCode 512 Python Solution

EasyLeetCode PremiumDatabase
Problem
#512
Reading time
2 min

The problem

For every player, report the device they used on the day of their first login. The Activity table has player_id (int), device_id (int), event_date (date) and games_played (int), with (player_id, event_date) as its primary key, so a player has at most one session per day. Return player_id and device_id.

Example

Input
Activity(player_id, device_id, event_date, games_played) = (1, 2, '2023-01-03', 5), (1, 5, '2023-01-06', 2), (2, 3, '2023-02-11', 1), (3, 1, '2023-01-05', 0), (3, 4, '2023-03-02', 4)
Output
(1, 2), (2, 3), (3, 1)
Explanation
Each row kept is the one whose event_date equals that player's earliest event_date.

Python solution

Python
import pandas as pd

def game_play_analysis(activity: pd.DataFrame) -> pd.DataFrame:
    first = activity.groupby('player_id', as_index=False)['event_date'].min()
    res = activity.merge(first, on=['player_id', 'event_date'], how='inner')
    return res[['player_id', 'device_id']].drop_duplicates()

Complexity

MeasureComplexity
TimeO(n log n) (typical)
SpaceO(n) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 512. Game Play Analysis II?
LeetCode 512. Game Play Analysis II is rated Easy on LeetCode.
What topics does LeetCode 512. Game Play Analysis II cover?
LeetCode 512. Game Play Analysis II is tagged Database on LeetCode.
Is LeetCode 512. Game Play Analysis II a premium problem?
Yes. LeetCode 512. Game Play Analysis II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview