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?- A. 3 2
- B. 4 -1
- C. 4 2
- 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
- Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to…
- Problem: Length of the longest common subsequence of THREE strings (3-D DP). python def lcs3(a, b, c): dp = [[[0] (len(c) + 1) for in…
- Problem: Length of the longest strictly increasing path in a matrix (moves in 4 directions), with memoised DFS. python from functools…
- Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two…
- Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i'…
- Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that…