DSA Heaps

Find Right Interval

For each interval, find the index of the interval whose start is the smallest value ≥ this interval's end — sorted array + binary search.

Medium
Time O(n log n) Space O(n)
LeetCode
4 min read
heaps binary-search sorting

Problem#

For each interval i, return the index j such that intervals[j].start >= intervals[i].end and is minimal. -1 if no such j.

Examples#

  • [[3,4],[2,3],[1,2]][-1, 0, 1]

Constraints#

  • 1 <= intervals.length <= 2 * 10^4.

Approach#

Collect (start, originalIndex) pairs, sort by start. For each interval i, binary-search for the smallest start ≥ intervals[i].end; map back to original index.

Solution#

Find Right Interval
class Solution {
public:
vector<int> findRightInterval(vector<vector<int>>& intervals) {
int n = intervals.size();
vector<pair<int,int>> starts(n);
for (int i = 0; i < n; ++i) starts[i] = {intervals[i][0], i};
sort(starts.begin(), starts.end());
vector<int> ans(n);
for (int i = 0; i < n; ++i) {
auto it = lower_bound(starts.begin(), starts.end(), make_pair(intervals[i][1], INT_MIN));
ans[i] = it == starts.end() ? -1 : it->second;
}
return ans;
}
};

Editorial#

The sentinel INT_MIN in the search key is a trick to break ties in favor of the smallest index satisfying the start ≥ end constraint when multiple intervals have the same start. lower_bound then returns the first qualifying entry. Heap pattern is equally valid (push all starts into a min-heap and lazy-pop), but binary search is simpler here.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.