You are given a list of intervals, where intervals[i] = [start, end]. No two intervals share a start.
For each interval i, find the interval j whose start is the smallest one that is still at or after the end of i. That j is the right interval of i; it may be i itself. Return a list where position i holds j, or −1 when no start is big enough.
Example 1
Input: intervals = [[3, 6], [1, 2], [6, 8], [4, 5]] Output: [2, 0, -1, 2] Why: [1, 2] gets [3, 6]; nothing starts at 8 or later
2 more examples and the constraints
Example 2
Input: intervals = [[5, 5]] Output: [0] Why: its own start 5 is at its end 5
Example 3
Input: intervals = [[-2, 0], [0, 3], [7, 9]] Output: [1, 2, -1] Why: 0 starts at the end of [-2, 0]; 7 is the first start ≥ 3
Constraints
- 1 ≤ number of intervals ≤ 20,000
- −1,000,000 ≤ start ≤ end ≤ 1,000,000
- Every start is different
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every pairO(n²)
- Sort + binary searchO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 20,000 intervals | Verdict |
|---|---|---|---|
| Check every pair | O(n²) | Mention it, then move on | |
| Sort + binary search | O(n log n) | Best; one sort, n searches |
n = number of intervals.
Edge cases to test
- An interval that is a point. [5, 5] starts at its own end, so it is its own right interval: 0.
- Start equal to end. [1, 3] and [3, 7]: a start of exactly 3 counts, so the answer for [1, 3] is 1.
- No start is big enough. The interval with the largest end often gets −1.
- Negative values. Ends and starts can be below zero; the search does not care.
Common mistakes
- Sorting the intervals themselves and returning positions in the sorted order instead of the original indices.
- Searching for a start strictly greater than the end, so [5, 5] and [1, 3] → [3, 7] are missed.
- Binary searching over ends instead of starts.
How to talk through it
- 1Clarify. Can an interval be its own right interval? Are starts unique? Which index do I return?
- 2Give the brute force. Scan all starts for each interval; O(n²), too slow for 20,000.
- 3Name the search. Each interval needs the smallest start ≥ its end: a lower bound on sorted starts.
- 4Code it. Sort (start, index) pairs, then binary search every end and map back to the index.
- 5Test out loud. Run a point interval like [5, 5] and an interval with no right one.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?