Find Right Interval - Problem

You are given an array of intervals, where intervals[i] = [start_i, end_i] and each start_i is unique.

The right interval for an interval i is an interval j such that start_j >= end_i and start_j is minimized.

Note that i may equal j.

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.

Input & Output

Example 1 — Basic Case
$ Input: intervals = [[1,2]]
Output: [-1]
💡 Note: There is only one interval, no right interval exists for [1,2], so return -1
Example 2 — Multiple Intervals
$ Input: intervals = [[3,4],[2,3],[1,2]]
Output: [-1,0,1]
💡 Note: For [3,4]: no interval starts >= 4, return -1. For [2,3]: [3,4] starts at 3 >= 3, return index 0. For [1,2]: [2,3] starts at 2 >= 2, return index 1
Example 3 — Self Reference
$ Input: intervals = [[1,4],[2,3],[3,4]]
Output: [-1,2,-1]
💡 Note: For [1,4]: no start >= 4, return -1. For [2,3]: [3,4] starts at 3 >= 3, return index 2. For [3,4]: no start >= 4, return -1

Constraints

  • 1 ≤ intervals.length ≤ 2 × 104
  • intervals[i].length == 2
  • -106 ≤ starti ≤ endi ≤ 106
  • The start point of each interval is unique.

Visualization

Tap to expand
Find Right Interval INPUT Intervals Array [1, 2] index 0 Interval Details: start_0 = 1 end_0 = 2 1 2 ALGORITHM STEPS 1 Sort by Start Create sorted list of (start, index) pairs 2 Binary Search For each end_i, find smallest start_j >= end_i 3 Check Result For interval [1,2]: end=2, need start>=2 4 No Match Found Only start=1 exists 1 < 2, return -1 Sorted Starts: (1, idx:0) FINAL RESULT Right Interval Indices [-1] Explanation: For interval [1, 2]: Need start_j >= 2 No such interval exists Result: -1 NO RIGHT INTERVAL Index 0 --> -1 Key Insight: The optimal solution uses sorting + binary search for O(n log n) time complexity. For single interval [1,2], since end=2 and only start=1 exists (1 < 2), no right interval can be found. The right interval requires start_j >= end_i, which is impossible here. Hence, result is [-1]. TutorialsPoint - Find Right Interval | Optimal Solution (Binary Search)
Asked in
Google 15 Facebook 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen