![]() |
VOOZH | about |
Given an array ranges[][] of size N x 2, where for every i, range[i][0] is the start and range[i][1] is the end of the range. For every range, find the index of the Next Optimal Range. For a range i which ends at a point X, all the ranges that have their starting points >= X will be the Next Optimal Range. In the case of multiple Next Optimal Range, the range with the smallest starting point is the most optimal. If there is no optimal range of any index i, then the answer for i-th index will be -1.
Note: The ranges have unique starting points.
Examples:
Input: ranges = [[-1, -1], [-2, 3], [3, 3]]
Output: [0,2,2]
Explanation: For i = 0, start = -1 and end = -1, so the only range which starts at or after -1, is the range [3, 3] which is at index 0.For i = 1, start = -2 and end = 3, so the only range which starts at or after 3, is the range [3, 3], which is at index. For i = 2, start = 3 and end = 3, so the only range which starts at or after 3, is the range [3, 3], which is at index 2.Input: ranges = [[-1, -1], [2, 3], [-3, 3], [-50, -20]]
Output: [1, -1, -1, 2]
Explanation: For i = 0, start = -1 and end = -1, so the only range which starts after at or after -1, is the range [2, 3] which is at index 1.For i = 1, start = 2 and end = 3, so no range starts at or after 3, therefore -1. For i = 2, start = -3 and end = 3, so no range starts at or after 3, therefore -1. For i = 3, start = -50 and end = -20, so the ranges which start at or after -20 are range [-3,3], [-1,1] and [2,3] so the we will consider range with smallest starting point, therefore the answer is the range [-3,3] which is at index 2.
Approach: To solve the problem follow the below idea:
This problem can be solved using Binary Search. Firstly, we can declare a map, say indexes which stores the index of every starting point. Now for every range i we can use using binary search to find the index of the range which has least starting point after the ending of i. If there is no range then the answer will be -1
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach:
1 -1 -1 2
Time Complexity: O(N*log N)
Auxiliary Space: O(N)