See the original problem on HackerRank.
Solutions
This is a problem on intervals. A brute force solution would involve checking every pair of talks to see if they overlap. We can iterate through each talk and compare it with every other talk. If any two talks overlap, the schedule is invalid. Two talks overlap if one starts before the other ends and vice versa. This results in a nested loop where each talk is compared against all others, leading to a quadratic time complexity.
A more efficient solution consists in sorting the input by their start time, and then checking if any interval overlaps in a single pass. This is as costly as the sorting algorithm that - in this case - is \(O(N \cdot logN)\).
Here is a C++ solution - we use a vector<pair<int, int>>
to store the intervals that is a common and simple representation:
|
|
We can replace the for loop with the standard algorithm adjacent_find
, which effectively finds two adjacent intervals that exhibit a specific property, such as overlapping:
|
|
The same solution in Python:
|
|