Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an integer hour (so you wait for the next whole hour). Find the minimum speed to arrive within hour (binary search).

Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an integer hour (so you wait for the next whole hour). Find the minimum speed to arrive within `hour` (binary search).
import math
def min_speed(dist, hour):
    def time(v):
        return sum(math.ceil(d / v) for d in dist[:-1]) + dist[-1] / v
    lo, hi, ans = 1, 10 ** 7, -1
    while lo <= hi:
        m = (lo + hi) // 2
        if time(m) <= hour: ans, hi = m, m - 1
        else: lo = m + 1
    return ans
print(min_speed([5, 3, 4, 2], 4.5), min_speed([1, 1, 1], 1.9))
What is printed?
  1. A. 3 2
  2. B. 4 -1
  3. C. 4 2
  4. D. 5 2

Correct answer: B. 4 -1

At speed 4: ceil(5/4) + ceil(3/4) + ceil(4/4) + 2/4 = 2 + 1 + 1 + 0.5 = 4.5 ≤ 4.5, while speed 3 gives 2 + 1 + 2 + 0.67 > 4.5. With three trains, the first two take at least 1 hour each, so 1.9 hours is impossible at any speed: −1.

More Coding Interview Problems questions

Exams that ask this topic