Problem Description
Given an array of intervals where each interval is represented as [start, end] and the start of each interval is unique, for each interval find the "right" interval. The "right" interval for an interval i is the interval j with the smallest start such that start_j is greater than or equal to end_i. If no such interval exists, return -1 for that interval.
Key Insights
- Every interval’s start is unique, which enables mapping back to the original indices after sorting.
- Sorting the intervals by their start value allows efficient searching.
- Binary search can be used to quickly find the smallest start that is greater than or equal to a given end value.
- The problem demands preserving the result order corresponding to the input order.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting and performing binary search for each interval. Space Complexity: O(n) for auxiliary data storage such as the sorted list of intervals and mapping between indices.
Solution
Sort the intervals based on their start values while keeping track of their original indices. For each interval in the original list, perform a binary search on the sorted list to find the smallest start that is greater than or equal to its end value. If such an interval is found, record its index; otherwise, record -1. This approach leverages sorting and binary search to efficiently find the right interval for each input interval.