#1454
Medium Database Active users
Database
36.6% acceptance
Mar 31, 2026
420
40
No description available.
Solution
Pandas
Time O(1)
Space O(1)
# Table: Accounts
#
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | id | int |
# | name | varchar |
# +---------------+---------+
# id is the primary key (column with unique values) for this table.
# This table contains the account id and the user name of each account.
#
#
#
# Table: Logins
#
# +---------------+---------+
# | Column Name | Type |
# +---------------+---------+
# | id | int |
# | login_date | date |
# +---------------+---------+
# This table may contain duplicate rows.
# This table contains the account id of the user who logged in and the login date. A user may log in multiple times in the day.
#
#
#
# Active users are those who logged in to their accounts for five or more consecutive days.
#
# Write a solution to find the id and the name of active users.
#
# Return the result table ordered by id.
#
# The result format is in the following example.
#
# Example 1:
# Input:
# Accounts table:
# +----+----------+
# | id | name |
# +----+----------+
# | 1 | Winston |
# | 7 | Jonathan |
# +----+----------+
# Logins table:
# +----+------------+
# | id | login_date |
# +----+------------+
# | 7 | 2020-05-30 |
# | 1 | 2020-05-30 |
# | 7 | 2020-05-31 |
# | 7 | 2020-06-01 |
# | 7 | 2020-06-02 |
# | 7 | 2020-06-02 |
# | 7 | 2020-06-03 |
# | 1 | 2020-06-07 |
# | 7 | 2020-06-10 |
# +----+------------+
# Output:
# +----+----------+
# | id | name |
# +----+----------+
# | 7 | Jonathan |
# +----+----------+
# Explanation:
# User Winston with id = 1 logged in 2 times only in 2 different days, so, Winston is not an active user.
# User Jonathan with id = 7 logged in 7 times in 6 different days, five of them were consecutive days, so, Jonathan is an active user.
import pandas as pd
def active_users(accounts: pd.DataFrame, logins: pd.DataFrame) -> pd.DataFrame:
if logins.empty:
return pd.DataFrame(columns=['id', 'name'])
logins = logins.drop_duplicates()
logins['login_date'] = pd.to_datetime(logins['login_date'])
logins = logins.sort_values(['id', 'login_date'])
logins['rank'] = logins.groupby('id')['login_date'].rank(method='dense')
logins['grp'] = logins['login_date'] - pd.to_timedelta(logins['rank'], unit='D')
consecutive = logins.groupby(['id', 'grp']).size().reset_index(name='cnt')
active_ids = consecutive[consecutive['cnt'] >= 5]['id'].unique()
result = accounts[accounts['id'].isin(active_ids)][['id', 'name']]
return result.sort_values('id')