VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bike-racing/

⇱ Minimum Time to Trigger Alarm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Time to Trigger Alarm

Last Updated : 23 Jul, 2025

A bike race is being organized with n bikers. The initial speed and the acceleration of each biker are provided in two arrays: a[] (initial speed) and b[] (acceleration). A biker is considered fast if their speed at any given hour is greater than or equal to a threshold value s. The total speed on the track for each hour is calculated by summing the speeds of all fast bikers at that hour. Once the total speed on the track reaches or exceeds a threshold value m, the safety alarm turns on. The task is to find the minimum number of hours after which the safety alarm will start.

Hint : We can compute the current speed using basic acceleration and speed formula and assuming uniform acceleration.
current speed = initial speed + acceleration * time

Examples:

Input: n = 3, m = 400, s = 120, a[] = [20, 50, 20], b[] = [20, 70, 90]
Output: 3
Explanation: Speeds of all the Bikers after every hour starting from 0
Biker1 = [20, 40, 60, 80, 100] 
Biker2 = [50, 120, 190, 260, 330]
Biker3 = [20, 110, 200, 290, 380]
Initial Speed on track  = 0 because none of the biker's speed is fast enough.
Speed on track after 1st Hour= 120
Speed on track after 2nd Hour= 190+200=390
Speed on track after 3rd Hour= 260+290=550
The Alarm will start at 3rd Hour.

Input: n = 2, m = 60, s = 120, a[] = [50, 30], b[] = [20, 40]
Output: 3

[Naive Approach] Direct Calculation Method - O(n * max(s, m)) and O(1) space

The approach iterates through each hour, calculating the speed of every biker at that particular hour. For each biker, the speed is computed as the initial speed plus the product of their acceleration and the hour. If a biker's speed meets or exceeds the threshold s, they are considered "fast" and their speed is added to the total speed on the track. The loop continues until the total speed reaches or exceeds the threshold m, at which point the function returns the number of hours required to activate the safety alarm.


Output
3

[Expected Approach] Using Binary Search - O(n * log(max(s, m))) and O(1) space

The problem can be solved using Binary Search based on the observation that if the total speed on the track reaches or exceeds M at hour i, it will continue to do so at hour i+1 due to the increasing speeds of the bikers.

Steps:

  1. Set the minimum time as 0 and the maximum time as max(s, m).
  2. Perform Binary Search over the time range:
    • For each midpoint hour, calculate the total speed by checking each biker's speed.
    • If the total speed is at least m, reduce the search range to the left; otherwise, increase the range to the right.
  3. Return the minimum hour when the total speed exceeds or equals m.

Output
3
Comment
Article Tags: