Open In App

Fastest Horse Query in a Race

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




// C++ code for the above approach:
#include <iostream>
#include <vector>
 
using namespace std;
 
// Function to find the fastest horse
// times for each query.
vector<int>
findFastestHorseTimes(vector<int>& finishTimes,
                      vector<vector<int> >& timeQueries)
{
    int numberOfHorses = finishTimes.size();
    int numberOfQueries = timeQueries.size();
 
    vector<int> queryResults(numberOfQueries);
 
    for (int q = 0; q < numberOfQueries; q++) {
        // Extract the start and end indices
        // for the current query.
        int queryStart = timeQueries[q][0] - 1;
        int queryEnd = timeQueries[q][1] - 1;
 
        // Initialize minTime with a
        // large value.
        int minTime = 1e9;
 
        // Iterate through the horse finish
        // times within the query range.
        for (int i = queryStart; i <= queryEnd; i++) {
 
            // Update minTime if a faster
            // time is found.
            minTime = min(minTime, finishTimes[i]);
        }
 
        // Store the minimum time as the
        // result for the current query.
        queryResults[q] = minTime;
    }
 
    // Return the results for all queries.
    return queryResults;
}
 
// Drivers code
int main()
{
    // Input data.
    int n = 10, q = 2;
    vector<int> finishTimes = { 380, 535, 314, 394, 402,
                                287, 379, 158, 157, 919 };
    vector<vector<int> > timeQueries
        = { { 3, 7 }, { 5, 7 } };
 
    // Find the fastest horse times
    // for the queries.
    vector<int> results
        = findFastestHorseTimes(finishTimes, timeQueries);
 
    // Display the results.
    for (int i = 0; i < results.size(); i++) {
        cout << results[i] << " ";
    }
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class Main {
    // Function to find the fastest horse times for each query.
    public static List<Integer> findFastestHorseTimes(List<Integer> finishTimes, List<List<Integer>> timeQueries) {
        // Get the number of horses and queries.
        int numberOfHorses = finishTimes.size();
        int numberOfQueries = timeQueries.size();
 
        // Initialize the results list.
        List<Integer> queryResults = new ArrayList<>(numberOfQueries);
 
        // Loop through each query.
        for (int q = 0; q < numberOfQueries; q++) {
            // Extract the start and end indices for the current query.
            int queryStart = timeQueries.get(q).get(0) - 1;
            int queryEnd = timeQueries.get(q).get(1) - 1;
 
            // Initialize minTime with a large value.
            int minTime = Integer.MAX_VALUE;
 
            // Iterate through the horse finish times within the query range.
            for (int i = queryStart; i <= queryEnd; i++) {
                // Update minTime if a faster time is found.
                minTime = Math.min(minTime, finishTimes.get(i));
            }
 
            // Store the minimum time as the result for the current query.
            queryResults.add(minTime);
        }
 
        // Return the results for all queries.
        return queryResults;
    }
 
    public static void main(String[] args) {
        // Input data.
        List<Integer> finishTimes = Arrays.asList(380, 535, 314, 394, 402, 287, 379, 158, 157, 919);
        List<List<Integer>> timeQueries = Arrays.asList(Arrays.asList(3, 7), Arrays.asList(5, 7));
 
        // Find the fastest horse times for the queries.
        List<Integer> results = findFastestHorseTimes(finishTimes, timeQueries);
 
        // Display the results.
        for (Integer result : results) {
            System.out.print(result + " ");
        }
    }
}


Python3




def find_fastest_horse_times(finish_times, time_queries):
    number_of_horses = len(finish_times)
    number_of_queries = len(time_queries)
 
    query_results = []
 
    for q in range(number_of_queries):
        # Extract the start and end indices for the current query.
        query_start = time_queries[q][0] - 1
        query_end = time_queries[q][1] - 1
 
        # Initialize min_time with a large value.
        min_time = float('inf')
 
        # Iterate through the horse finish times within the query range.
        for i in range(query_start, query_end + 1):
            # Update min_time if a faster time is found.
            min_time = min(min_time, finish_times[i])
 
        # Store the minimum time as the result for the current query.
        query_results.append(min_time)
 
    # Return the results for all queries.
    return query_results
 
# Drivers code
def main():
    # Input data.
    finish_times = [380, 535, 314, 394, 402, 287, 379, 158, 157, 919]
    time_queries = [[3, 7], [5, 7]]
 
    # Find the fastest horse times for the queries.
    results = find_fastest_horse_times(finish_times, time_queries)
 
    # Display the results.
    for result in results:
        print(result, end=" ")
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to find the fastest horse times for each query.
    static List<int> FindFastestHorseTimes(List<int> finishTimes, List<List<int>> timeQueries)
    {
        int numberOfHorses = finishTimes.Count;
        int numberOfQueries = timeQueries.Count;
 
        List<int> queryResults = new List<int>(numberOfQueries);
 
        for (int q = 0; q < numberOfQueries; q++)
        {
            // Extract the start and end indices for the current query.
            int queryStart = timeQueries[q][0] - 1;
            int queryEnd = timeQueries[q][1] - 1;
 
            // Initialize minTime with a large value.
            int minTime = int.MaxValue;
 
            // Iterate through the horse finish times within the query range.
            for (int i = queryStart; i <= queryEnd; i++)
            {
                // Update minTime if a faster time is found.
                minTime = Math.Min(minTime, finishTimes[i]);
            }
 
            // Store the minimum time as the result for the current query.
            queryResults.Add(minTime);
        }
 
        // Return the results for all queries.
        return queryResults;
    }
 
    // Drivers code
    static void Main()
    {
        // Input data.
        List<int> finishTimes = new List<int> { 380, 535, 314, 394, 402, 287, 379, 158, 157, 919 };
        List<List<int>> timeQueries = new List<List<int>> { new List<int> { 3, 7 }, new List<int> { 5, 7 } };
 
        // Find the fastest horse times for the queries.
        List<int> results = FindFastestHorseTimes(finishTimes, timeQueries);
 
        // Display the results.
        for (int i = 0; i < results.Count; i++)
        {
            Console.Write(results[i] + " ");
        }
 
        Console.ReadLine();
    }
}


Javascript




function findFastestHorseTimes(finishTimes, timeQueries) {
    const numberOfHorses = finishTimes.length;
    const numberOfQueries = timeQueries.length;
 
    const queryResults = [];
 
    for (let q = 0; q < numberOfQueries; q++) {
        // Extract the start and end indices for the current query.
        const queryStart = timeQueries[q][0] - 1;
        const queryEnd = timeQueries[q][1] - 1;
 
        // Initialize minTime with a large value.
        let minTime = Infinity;
 
        // Iterate through the horse finish times within the query range.
        for (let i = queryStart; i <= queryEnd; i++) {
            // Update minTime if a faster time is found.
            minTime = Math.min(minTime, finishTimes[i]);
        }
 
        // Store the minimum time as the result for the current query.
        queryResults.push(minTime);
    }
 
    // Return the results for all queries.
    return queryResults;
}
 
// Driver code
function main() {
    // Input data.
    const finishTimes = [380, 535, 314, 394, 402, 287, 379, 158, 157, 919];
    const timeQueries = [[3, 7], [5, 7]];
 
    // Find the fastest horse times for the queries.
    const results = findFastestHorseTimes(finishTimes, timeQueries);
 
    // Display the results.
    console.log(results.join(' '));
}
 
// Execute the main function if this script is the main module.
if (require.main === module) {
    main();
}


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads