You are given a collection of intervals represented as a list of lists, where each interval is a list [start, end]
. For each interval, you need to find the smallest interval in the collection that starts after the end of this interval. Specifically, for each interval i
, find an interval j
such that intervals[i][1] <= intervals[j][0]
and intervals[j][0]
is the smallest possible value. If no such interval exists, the answer for that interval is -1
.
Return an array of indices representing the answer for each interval. If there is more than one correct answer, you can return any of them.
intervals = [[1, 2], [2, 3], [3, 4]]
Output: [-1, 2, -1]
1 <= intervals.length <= 2 * 10^4
intervals[i].length == 2
-10^6 <= intervals[i][0] <= intervals[i][1] <= 10^6
-1
if no such interval exists.[start, end]
.Here’s the Python implementation:
from bisect import bisect_left
def findRightInterval(intervals):
start_points = sorted((start, i) for i, (start, end) in enumerate(intervals))
n = len(intervals)
result = [-1] * n # To store the results
for i, (start, end) in enumerate(intervals):
# Find the first interval whose start is >= the end of the current interval
idx = bisect_left(start_points, (end,))
if idx < n:
result[i] = start_points[idx][1]
return result
# Example usage:
intervals = [[1, 2], [2, 3], [3, 4]]
print(findRightInterval(intervals)) # Output: [-1, 2, -1]
start_points
will take O(n log n)
, where n
is the number of intervals.O(log n)
. Since we do this for each of the n
intervals, the total cost for searching is O(n log n)
.Thus, the overall time complexity is O(n log n)
.
This approach ensures efficient handling of the problem within the given constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?