436. Find Right Interval
LeetCode 436. Find Right Interval
Description
You are given an array of intervals
, where intervals[i] = [starti, endi]
and each starti
is unique.
The right interval for an interval i
is an interval j
such that startj >= endi
and startj
is minimized.
Return an array of right interval indices for each interval i
. If no right interval exists for interval i
, then put -1
at index i
.
Example 1:
Example 2:
Example 3:
Constraints:
1 <= intervals.length <= 2 * 10^4
intervals[i].length == 2
-10^6 <= starti <= endi <= 10^6
The start point of each interval is unique.
Tags
Binary Search
Solution
For each interval, we need to find if a value which is equal to or just greater than the interval's right interval exists in all left intervals. Thus, we needed a data structure that can search a given value very fast, and it can return an index where the value is either just greater than the target or return -1. Such data structure is a sorted array.
Based on the above analysis, the first step is to build a sorted array which contains all left intervals. Also, we need a hash table to store the map from a left interval to its index in intervals. The second step is to check if the search result of each right interval among the sorted array is valid. If the returned index is equal to the length of the array, we assign -1 to the corresponding position on the result array. Otherwise, assign start2idx[starts[startIdx]]
to it.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?