![]() |
VOOZH | about |
Given ‘N’ horses running in ‘N’ different lanes numbered from 1 to ‘N’. You are given an array “FINISHTIME” containing ‘N’ integers where “FINISHTIME[i]” represents the time taken by the ith horse to complete the race. Also given are ‘Q’ queries, each containing two integers each, ‘L’ and ‘R’. For each query, return the time taken by the fastest horse amongst the horses with numbers {L, L + 1, L + 2, …., R - 1, R} to complete the race. The fastest horse is the one that takes the minimum time to finish the race.
Examples:
Input: N = 10, Q = 2, FINISHTIME = {380, 535, 314, 394, 402, 287, 379, 158, 157, 919}, Queries[][] = {{3, 7}, {5, 7}}
Output: {287, 287}
Explanation: First Query: The shortest time among the horses in the range [314, 394, 402, 287, 379] is 287.
Second Query: The quickest time among the horses in the range [402, 287, 379] is 287.Input: N = 4, Q = 2, FINISHTIME = {2, 6, 4, 8}, Queries[][] = {{1, 3}, {3, 4}}
Output: {2, 4}
Explanation: First Query: The shortest time among the horses in the range [2, 6, 4] is 2.
Second Query: The quickest time among the horses in the range [4, 8] is 4.
Naive Approach: Below is the mentioned idea for the basic approach:
Finding the minimum finishing time among horses within specified query ranges and stores the results for all queries.
Below is the code explanation to solve the problem:
Below is the C++ implementation of the above approach:
287 287
Time Complexity: O(N + Q * log(N)), where ‘N’ denotes the number of horses and ‘Q’ denotes the number of queries.
Auxiliary Space: O(N + Q), where ‘N’ denotes the number of horses and ‘Q’ denotes the number of queries.