Minimum Time to Visit All Houses - Problem
Imagine you're planning an efficient route through a circular neighborhood where houses are connected by roads of varying lengths. You start at house 0 and need to visit a sequence of houses as quickly as possible.
The neighborhood has a unique road system:
- Forward roads: Each house
iconnects to house(i+1) % nwith distanceforward[i]meters - Backward roads: Each house
iconnects to house(i-1+n) % nwith distancebackward[i]meters
You walk at 1 meter per second and need to visit houses in the exact order specified by the queries array. Your goal is to find the minimum total time to complete this journey.
Key insight: For each step in your journey, you can choose to go clockwise (forward) or counterclockwise (backward) around the circle to reach your destination faster!
Input & Output
example_1.py โ Basic Circle Navigation
$
Input:
forward = [5, 7, 3], backward = [3, 5, 2], queries = [1, 2, 0]
โบ
Output:
13
๐ก Note:
Start at house 0. Go to house 1: min(5, 3+5+2) = min(5, 10) = 5. Go to house 2: min(7, 5) = 5. Go to house 0: min(3, 7+5) = min(3, 12) = 3. Total: 5+5+3 = 13
example_2.py โ Same House Query
$
Input:
forward = [4, 6], backward = [2, 3], queries = [0, 1, 0]
โบ
Output:
6
๐ก Note:
Start at house 0. Stay at house 0: 0 time. Go to house 1: min(4, 2) = 2. Go to house 0: min(6, 3) = 3. Total: 0+2+4 = 6 (Note: 2+4=6, there was an error in explanation)
example_3.py โ Large Circle
$
Input:
forward = [1, 1, 1, 1], backward = [1, 1, 1, 1], queries = [2]
โบ
Output:
2
๐ก Note:
Start at house 0, need to go to house 2. Both clockwise (1+1=2) and counterclockwise (1+1=2) take same time. Choose either: 2
Constraints
- 1 โค n โค 105
- 1 โค forward[i], backward[i] โค 104
- 1 โค queries.length โค 105
- 0 โค queries[i] < n
- All distances are positive integers
Visualization
Tap to expand
Understanding the Visualization
1
Preprocess
Calculate cumulative distances for both directions around the circle
2
Query
For each destination, instantly compute both clockwise and counterclockwise distances
3
Optimize
Always choose the shorter path to minimize travel time
4
Accumulate
Add the chosen distance to total time and move to next query
Key Takeaway
๐ฏ Key Insight: Pre-computing prefix sums transforms expensive O(n) distance calculations into instant O(1) lookups, making the solution efficient even for large inputs!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code