The watched hours
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- strings
- lists
- sorting
Problem
The house on Elm Street was watched for several days straight, in shifts by different officers, and sometimes two shifts overlap. Captain Ward wants to know how many hours someone was actually watching.
You get shifts, a list of strings "start-end" with whole hours counted from the moment the stakeout began: "30-36" runs from hour 30 to hour 36 and covers 6 hours. The start is always less than the end, and the shifts come in any order. Return an integer: the hours covered by at least one shift, counting only once the hours two officers shared. With "9-12", "11-14" and "20-22" you return 7: 5 from 9 to 14, plus 2.
A shift can fit entirely inside another: "8-18" and "10-12" give 10. Two shifts that touch, "9-12" and "12-15", give 6, with no gap and no hour counted twice. With no shifts, return 0.
Examples
Two overlap and one apart
["9-12", "11-14", "20-22"] → 7
One shift inside another
["8-18", "10-12"] → 10
Two shifts that touch
["9-12", "12-15"] → 6
None of them overlap
["4-6", "30-33", "60-70"] → 15
Two- and three-digit hours
["130-136", "95-101", "98-104"] → 15
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def watched_hours(shifts):
passJavaScript
function watchedHours(shifts) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.