The Minimum Time to Visit All Houses problem gives you positions of houses on a number line. Starting from the first house, find the minimum time to visit all houses. You can move at speed 1 in either direction. This Minimum Time to Visit All Houses coding problem uses prefix sums to efficiently compute minimum traversal costs for ranges of houses.
Salesforce asks this to test the ability to translate a geometric traversal problem into a prefix sum calculation. The key observation — that visiting houses in sorted order with a single traversal (going left first then right, or right first then left) gives the optimal strategy — ties the problem to prefix sum computation. The array and prefix sum interview pattern is central.
Prefix sum with sorted traversal. Sort house positions. The optimal strategy is to go in one direction first (covering all left houses), return to the start, then go in the other direction (covering all right houses) — or vice versa. Use prefix sums to quickly compute the total distance for each split point. For each possible "turning point," compute: 2 * min(left_range, right_range) + max(left_range, right_range).
Houses at positions: [2, 7, 4, 1, 9]. Sort: [1, 2, 4, 7, 9]. Start at house[0] = 1. All houses are to the right. Total distance = 9 - 1 = 8 (just move right).
Mixed positions: [3, -1, 5, 0] → sorted relative to start. Compute min time to visit all going right then left or left then right using prefix sums.
2 * shorter_direction + longer_direction.Number-line traversal problems are solved cleanly with prefix sums after sorting. The fundamental insight: every house visited in one direction costs its distance from start; if you need to cover both directions, you backtrack the shorter one and pay it twice. Practice computing "minimum traversal cost to cover all points on a number line" — it's a recurring pattern in delivery routing, robot movement, and array traversal problems. Prefix sums make range-sum computation O(1) after O(n) preprocessing.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Range Addition | Medium | Solve | |
| Product of Array Except Self | Medium | Solve | |
| Apply Operations to Make All Array Elements Equal to Zero | Medium | Solve | |
| Can You Eat Your Favorite Candy on Your Favorite Day? | Medium | Solve | |
| Corporate Flight Bookings | Medium | Solve |