Find Total Time Spent by Each Employee — LeetCode 1741 Python Solution

EasyDatabase
Problem
#1741
Reading time
2 min

Table schema

SQL
Table: Employees +-------------+------+ | Column Name | Type | +-------------+------+ | emp_id | int | | event_day | date | | in_time | int | | out_time | int | +-------------+------+ (emp_id, event_day, in_time) is the primary key (combinations of columns with unique values) of this table. The table shows the employees' entries and exits in an office.

Example

SQL
+-------------+------+
| Column Name | Type |
+-------------+------+
| emp_id      | int  |
| event_day   | date |
| in_time     | int  |
| out_time    | int  |
+-------------+------+
(emp_id, event_day, in_time) is the primary key (combinations of columns with unique values) of this table.
The table shows the employees' entries and exits in an office.
event_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute at which they left the office.
in_time and out_time are between 1 and 1440.
It is guaranteed that no two events on the same day intersect in time, and in_time < out_time.

Python solution

Python
import duckdb
import pandas as pd

def solution(employees: pd.DataFrame) -> pd.DataFrame:
    con = duckdb.connect()
    con.register("Employees", employees)
    return con.execute("""SELECT event_day AS day, emp_id, SUM(out_time - in_time) AS total_time
FROM Employees
GROUP BY 1, 2;""").df()

Complexity

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

Related problems

Frequently asked questions

How hard is LeetCode 1741. Find Total Time Spent by Each Employee?
LeetCode 1741. Find Total Time Spent by Each Employee is rated Easy on LeetCode.
What topics does LeetCode 1741. Find Total Time Spent by Each Employee cover?
LeetCode 1741. Find Total Time Spent by Each Employee is tagged Database on LeetCode.

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