💡 Mid speed recalculates candidate speed in the narrowed range.
Line:mid = (low + high) / 2
💡 The search space continues to halve, approaching the minimum speed.
compare
Check Feasibility at Mid Speed
Check if arriving on time is possible at speed 312,500.
💡 Feasibility check guides the binary search direction.
Line:if can_arrive(dist, hour, mid):
💡 Still feasible, so the algorithm tries smaller speeds.
shrink
Update High Bound to Mid
Update high to mid = 312,500 to narrow the search space.
💡 Upper bound moves closer to the minimum feasible speed.
Line:high = mid
💡 Speeds above mid are eliminated.
shrink
Converge to Minimum Speed
The binary search continues halving the search space until high - low <= epsilon, converging near 1.0.
💡 The algorithm stops when the search space is sufficiently small to determine the minimum speed.
Line:while high - low > epsilon:
💡 The minimum feasible speed is found within the precision threshold.
reconstruct
Return Final Answer
Return the ceiling of high, which is 1, as the minimum integer speed to arrive on time.
💡 Ceiling ensures the speed is an integer that meets the time requirement.
Line:return ceil(high)
💡 The algorithm outputs the smallest integer speed that allows on-time arrival.
from math import ceil
def can_arrive(dist, hour, speed):
total_time = 0.0
for i in range(len(dist) - 1): # STEP 3,6,9,12,15
total_time += ceil(dist[i] / speed)
total_time += dist[-1] / speed
return total_time <= hour
def min_speed_on_time(dist, hour):
low, high = 1.0, 10**7 # STEP 1
epsilon = 1e-6
while high - low > epsilon: # STEP 17
mid = (low + high) / 2 # STEP 2,5,8,11,14
if can_arrive(dist, hour, mid): # STEP 3,6,9,12,15
high = mid # STEP 4,7,10,13,16
else:
low = mid
return ceil(high) # STEP 18
if __name__ == '__main__':
print(min_speed_on_time([1,3,2], 6)) # Expected: 1
📊
Minimum Speed to Arrive on Time - Watch the Algorithm Execute, Step by Step
Watching each step shows how binary search on a continuous answer space works, revealing the logic behind choosing speeds and eliminating impossible ranges.
Step 1/18
·Active fill★Answer cell
1
0
lo
3
1
2
2
Next: lo=1 hi=10000000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=10000000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=5000000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=5000000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=5000000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=2500000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=2500000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=2500000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=1250000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=1250000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=1250000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=625000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=625000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=625000
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=312500
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=312500
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=1.0000005
Target: 6
1
0
lo
3
1
2
2
Next: lo=1 hi=1.0000005
Key Takeaways
✓ Binary search on a continuous answer space efficiently narrows down the minimum feasible speed by halving the search range each iteration.
This insight is hard to see from code alone because the floating-point search space and feasibility checks are abstract concepts without visualization.
✓ Feasibility checks using ceil for all but the last segment ensure the algorithm respects the problem's rounding constraints.
Understanding why ceil is used only for intermediate segments clarifies how travel time is calculated and why the last segment differs.
✓ The decision to move the high or low bound depends entirely on feasibility, illustrating a classic binary search elimination pattern.
Seeing the search space shrink visually helps learners grasp how decisions prune impossible speeds.
Practice
(1/5)
1. Consider the following Python code implementing the min-heap approach to find the kth smallest element in a sorted matrix. Given the matrix [[1,3],[2,4]] and k = 3, what value does the function return?
easy
A. 2
B. 4
C. 3
D. 1
Solution
Step 1: Initialize min-heap with first elements
Push (1,0,0) and (2,1,0) into heap.
Step 2: Extract elements until count == k
Pop 1 (count=1), push 3 from row 0; pop 2 (count=2), push 4 from row 1; pop 3 (count=3), return 3.
Final Answer:
Option C -> Option C
Quick Check:
Third smallest element is 3 [OK]
Hint: Trace heap pops and pushes carefully [OK]
Common Mistakes:
Off-by-one counting of popped elements
Returning wrong popped value
Confusing row and column indices
2. Consider the following recursive binary search code for finding the insert position of target = 2 in nums = [1, 3, 5, 6]. What is the final returned value?
Hint: Follow recursive calls and base case carefully [OK]
Common Mistakes:
Returning right instead of left at base case
Off-by-one in mid calculation
Confusing left and right updates
3. Suppose the array is no longer sorted but you still need to find the first and last positions of a target value. Which approach is correct and efficient?
hard
A. Use a linear scan to find first and last occurrences directly
B. Sort the array first, then apply modified binary search to find positions
C. Use the same modified binary search approach since it works on any array
D. Use a hash map to store all indices of each value, then retrieve target positions
Solution
Step 1: Recognize that binary search requires sorted array
Without sorting, binary search cannot guarantee correct positions.
Step 2: Evaluate alternatives
Sorting changes indices, so linear scan or hash map are options; linear scan is simplest and O(n).
Step 3: Compare efficiency and correctness
Linear scan finds first and last positions in one pass without modifying array.
Final Answer:
Option A -> Option A
Quick Check:
Binary search requires sorted input; linear scan works otherwise [OK]
Hint: Binary search needs sorted array; linear scan works otherwise [OK]
Common Mistakes:
Trying binary search on unsorted array
Sorting and losing original indices
Overcomplicating with hash maps
4. Suppose Koko can eat bananas from multiple piles simultaneously each hour (i.e., she can split her eating speed across piles). How does this change the approach to find the minimum eating speed to finish within h hours?
hard
A. Feasibility check simplifies to total bananas ≤ speed * h, so minimum speed = ceil(total / h)
B. We must use dynamic programming to consider all pile combinations per hour
C. The original binary search with feasibility check still applies without changes
D. Binary search is invalid; a greedy approach is required instead
Solution
Step 1: Understand the new eating model
Koko can split speed across piles simultaneously, so total bananas eaten per hour equals speed.
Step 2: Simplify feasibility condition
To finish in h hours, total bananas ≤ speed * h, so minimum speed = ceil(total bananas / h).
Step 3: Conclude algorithm change
No binary search needed; direct calculation suffices.
Final Answer:
Option A -> Option A
Quick Check:
Splitting speed removes per-pile constraints, simplifying problem [OK]
Hint: Splitting speed means total bananas divided by hours [OK]
Common Mistakes:
Applying original binary search blindly
Overcomplicating with DP
5. Suppose the problem is modified so that x can be negative, and you want to return the integer square root of its absolute value. Which modification to the Newton's method code below correctly handles this variant without breaking the algorithm?
hard
A. Remove the base case check and rely on the loop to handle all x.
B. Change the loop condition to 'while guess * guess >= x' to handle negatives.
C. Add 'x = abs(x)' at the start and keep the rest unchanged.
D. Use floating point division instead of integer division to handle negatives.
Solution
Step 1: Understand the problem change
Allowing negative x means we must compute the integer square root of |x|.
Step 2: Modify input safely
Adding x = abs(x) at the start ensures the algorithm works unchanged on non-negative inputs.
Step 3: Avoid incorrect changes
Removing base cases or changing loop conditions breaks correctness; floating point division violates problem constraints.
Final Answer:
Option C -> Option C
Quick Check:
Absolute value conversion preserves algorithm correctness [OK]
Hint: Convert input to non-negative before applying integer sqrt [OK]
Common Mistakes:
Removing base cases
Changing loop condition incorrectly
Using float division causing precision errors
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.