VOOZH about

URL: https://www.geeksforgeeks.org/dsa/fastest-horse-query-in-a-race/

⇱ Fastest Horse Query in a Race - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Fastest Horse Query in a Race

Last Updated : 25 Jan, 2024

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:

  • We have a list of finish times for each horse and a set of time queries. Each query consists of a start index and an end index, representing a range of horses to consider.
  • For each time query, we extract the start and end indices.
  • We initialize a variable minTime with a large value (1e9). This variable will be used to keep track of the minimum time found within the query range.
  • We iterate through the horse finish times, specifically within the range defined by the query's start and end indices.
  • For each horse time within the range, we update minTime if a faster time is found. This ensures that we are continuously tracking the fastest time within the query range.
  • Once we've gone through all the horse times within the query range, we store the minimum time as the result for the current query in the queryResults vector.
  • After processing all queries, we return the queryResults vector containing the minimum times for each query.

Below is the C++ implementation of the above approach:


Output
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.

Comment