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, house i is connected to house i + 1 via a road with length forward[i] meters. Additionally, house n - 1 is connected back to house 0 via a road with length forward[n - 1] meters, completing the circle.
  • For all 1 <= i <= n - 1, house i is connected to house i - 1 via a road with length backward[i] meters. Additionally, house 0 is connected back to house n - 1 via a road with length backward[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
Circular Houses Problem0123F:3B:5Forward: [3,1,2,4]Backward: [5,2,1,3]Queries: [1,2,0]0→1: min(3,5) = 31→2: min(1,2) = 12→0: min(6,1) = 1Total Time: 3 + 1 + 1 = 5
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
Asked in
Google 15 Amazon 12 Meta 8
8.5K Views
Medium Frequency
~25 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen