Leetcode 436. Find Right Interval
Given a collection of intervals, find the minimum interval’s index for each interval such that the start point of this interval is greater than or equal to the end point of the given interval. If no such interval exists, return -1.
You may assume intervals’ end points are all unique.
Given interval list intervals
:
[ [1,2], [2,3], [3,4] ]
For each interval, you need to output the index of the minimum interval that has a start point greater than or equal to the end point of the current interval. Therefore, the output should be:
[-1, 0, 1]
Q: Can the intervals be overlapping? A: Yes.
Q: Are the intervals guaranteed to be sorted? A: No, intervals are not guaranteed to be sorted.
Q: What is the range of the interval values? A: The interval values are arbitrary integers, but you can assume a reasonable constraint such that they fit within typical integer ranges.
Q: Is there any restriction on the size of the input array? A: The size of the intervals array is not explicitly restricted, but it can be assumed to fit within the constraints of typical coding interview problems (e.g., up to thousands of intervals).
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
vector<int> findRightInterval(vector<vector<int>>& intervals) {
int n = intervals.size();
vector<tuple<int, int, int>> sortedIntervals;
// Step 1: Create tuples of (start, end, index)
for (int i = 0; i < n; i++) {
sortedIntervals.emplace_back(intervals[i][0], intervals[i][1], i);
}
// Step 2: Sort tuples by start times
sort(sortedIntervals.begin(), sortedIntervals.end());
vector<int> result(n, -1);
// Step 3: Perform binary search for each interval
for (int i = 0; i < n; i++) {
int end = intervals[i][1];
int lo = 0, hi = n - 1;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (get<0>(sortedIntervals[mid]) < end) {
lo = mid + 1;
} else {
hi = mid;
}
}
if (get<0>(sortedIntervals[lo]) >= end) {
result[i] = get<2>(sortedIntervals[lo]);
} else {
result[i] = -1;
}
}
return result;
}
int main() {
vector<vector<int>> intervals = \{\{1, 2}, {2, 3}, {3, 4}};
vector<int> result = findRightInterval(intervals);
for (int idx : result) {
cout << idx << " ";
}
cout << endl;
return 0;
}
Overall, the time complexity is O(n log n).
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?