-
Notifications
You must be signed in to change notification settings - Fork 17
/
employee-free-time.py
51 lines (40 loc) · 1.53 KB
/
employee-free-time.py
1
2
3
4
5
6
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
from dataclasses import dataclass
from typing import List, Tuple
# Definition for an Interval.
@dataclass
class Interval:
start: int
end: int
class Solution:
def employeeFreeTime(self, schedule: List[List[Interval]]) -> List[Interval]:
points: List[Tuple[int, int]] = []
# Interval starts - increase the number of intervals starting from here
# Interval ends - decrease the number of intervals starting from here
for intervals in schedule:
for interval in intervals:
points.append((interval.start, 1))
points.append((interval.end, -1))
# Sort all the points, so we can tell how many intervals exist in any
# particular point
points.sort()
free_times: List[Interval] = []
start = -1
count = 0
# Go over all points, keeping track on places where there are no
# intervals exist anymore
for position, adj in points:
count += adj
if count == 0:
# Start of the free interval
if start == -1:
start = position
else:
# Reset start, as this point is not a valid start anymore
if start == position:
start = -1
# Start has been set before, free interval is over, add it to
# the answer
if start != -1:
free_times.append(Interval(start, position))
start = -1
return free_times