Problem
Table: EmployeeShifts
+------------------+----------+
| Column Name | Type |
+------------------+----------+
| employee_id | int |
| start_time | datetime |
| end_time | datetime |
+------------------+----------+
(employee_id, start_time) is the unique key for this table.
This table contains information about the shifts worked by employees, including the start time, and end time.
Write a solution to analyze overlapping shifts for each employee. Two shifts are considered overlapping if they occur on the same date and one shift’s
end_time
is later than another shift’s start_time
.
For each employee , calculate the following:
- The maximum number of shifts that overlap at any given time.
- The total duration of all overlaps in minutes.
Return the result table ordered by employee_id
inascending order.
The query result format is in the following example.
Example 1:
|
|
Solution
Method 1 – Sweep Line Algorithm with Event Processing
Intuition
To find the maximum number of overlapping shifts and the total overlap duration for each employee, we can treat each shift’s start and end as events. By processing these events in order, we can track how many shifts are active at any time and sum up the durations where more than one shift overlaps.
Approach
- For each employee, group their shifts by date (since overlaps are only counted on the same date).
- For each date:
- Create a list of events: each shift’s start (+1) and end (-1).
- Sort all events by time.
- Sweep through the events, maintaining a counter of active shifts.
- Track the maximum number of active shifts.
- For total overlap duration, whenever the active count is 2 or more, add the time difference to the total.
- Sum the total overlap duration and maximum overlap for all dates for each employee.
- Return the results ordered by employee_id.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n log n)
per employee, wheren
is the number of shifts, due to sorting events for each employee and date. - 🧺 Space complexity:
O(n)
for storing events and intermediate results per employee.