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 i connects to house (i+1) % n with distance forward[i] meters
  • Backward roads: Each house i connects to house (i-1+n) % n with distance backward[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
0123Forward: 5Backward: 10Prefix SumsForward: [0,5,12,15,18]Backward: [0,3,8,10,18]Distance = O(1) lookup!OptimizationClockwise: prefix[target] - prefix[current]Counter: Use modular arithmeticChoose: min(clockwise, counter)๐Ÿ  Minimum Time to Visit All Houses
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!
Asked in
Google 35 Amazon 28 Microsoft 22 Meta 18
24.0K Views
Medium Frequency
~18 min Avg. Time
890 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