Minimum Time to Visit All Houses - Problem
You are given two integer arrays forward and backward, both of size n. You are also given another integer array queries.
There are n houses arranged in a circle. The houses are connected via roads in a special arrangement:
- For all
0 <= i <= n - 2, houseiis connected to housei + 1via a road with lengthforward[i]meters. Additionally, housen - 1is connected back to house0via a road with lengthforward[n - 1]meters, completing the circle. - For all
1 <= i <= n - 1, houseiis connected to housei - 1via a road with lengthbackward[i]meters. Additionally, house0is connected back to housen - 1via a road with lengthbackward[0]meters, completing the circle.
You can walk at a pace of one meter per second. Starting from house 0, find the minimum time taken to visit each house in the order specified by queries. Return the minimum total time taken to visit the houses.
Input & Output
Example 1 — Basic Circular Path
$
Input:
forward = [3,1,2,4], backward = [5,2,1,3], queries = [1,2,0]
›
Output:
11
💡 Note:
Start at house 0. Go to house 1 (min(3,5)=3), then to house 2 (min(1,2)=1), then to house 0 (min(6,1)=1). Total: 3+1+1=5
Example 2 — Same House Query
$
Input:
forward = [2,3], backward = [1,4], queries = [0,1,0]
›
Output:
3
💡 Note:
Start at house 0. Stay at house 0 (0 time), go to house 1 (min(2,4)=2), return to house 0 (min(3,1)=1). Total: 0+2+1=3
Example 3 — Larger Circle
$
Input:
forward = [1,2,3,4,5], backward = [6,5,4,3,2], queries = [2,4,1]
›
Output:
8
💡 Note:
Start at house 0. Go to house 2 (min(3,9)=3), then to house 4 (min(9,6)=6), then to house 1 (min(9,1)=1). Total: 3+6+1=10
Constraints
- 1 ≤ forward.length = backward.length = n ≤ 1000
- 1 ≤ forward[i], backward[i] ≤ 1000
- 1 ≤ queries.length ≤ 1000
- 0 ≤ queries[i] < n
Visualization
Tap to expand
Understanding the Visualization
1
Input
Circular houses with forward/backward road lengths and query sequence
2
Process
For each query, calculate minimum time between clockwise and counterclockwise paths
3
Output
Total minimum time to visit all houses in query order
Key Takeaway
🎯 Key Insight: Use prefix sums to calculate any segment distance in O(1) time, avoiding redundant path calculations in the circular arrangement
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code