Skip to main content

Minimum Time to Visit All Houses - Solution & Explanation

MediumPremiumFree on FleetCodeArrayPrefix Sum3 min readAsked at: Salesforce
Practice this problem

Problem Statement

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.

 

Example 1:

Input: forward = [1,4,4], backward = [4,1,2], queries = [1,2,0,2]

Output: 12

Explanation:

The path followed is 0(0)1(1) →​​​​​​​ 2(5) 1(7) ​​​​​​​ 0(8) 2(12).

Note: The notation used is node(total time), represents forward road, and represents backward road.

Example 2:

Input: forward = [1,1,1,1], backward = [2,2,2,2], queries = [1,2,3,0]

Output: 4

Explanation:

The path travelled is 0 →​​​​​​​ 1 →​​​​​​​ 2 →​​​​​​​ 30. Each step is in the forward direction and requires 1 second.

 

Constraints:

  • 2 <= n <= 105
  • n == forward.length == backward.length
  • 1 <= forward[i], backward[i] <= 105
  • 1 <= queries.length <= 105
  • 0 <= queries[i] < n
  • queries[i] != queries[i + 1]
  • queries[0] is not 0.

Approach Overview

Problem Overview: You are given an array representing houses and the time required to move between them. The task is to compute the minimum total time needed to visit all houses while accounting for travel costs between indices. The key challenge is efficiently calculating cumulative travel time across ranges of houses.

Approach 1: Direct Range Summation (Brute Force) (Time: O(n^2), Space: O(1))

A straightforward method computes the travel time between houses by summing the required movement cost each time you move across a range. For every step or transition, iterate through the array segment and accumulate the cost manually. This approach repeatedly recalculates the same partial sums, which leads to quadratic behavior in the worst case. While simple to implement, it becomes inefficient when the number of houses grows large.

Approach 2: Prefix Sum Optimization (Time: O(n), Space: O(n))

The optimal strategy precomputes cumulative travel times using a prefix sum array. Each index stores the total time required to reach that point from the start. Once built, the travel time between any two houses can be computed in constant time using prefix[r] - prefix[l]. Instead of repeatedly iterating over ranges, you perform a single pass to build the prefix array and then use fast lookups during the traversal logic.

This technique is widely used when working with cumulative ranges in arrays. The key insight is that many travel calculations overlap. Storing cumulative totals eliminates redundant work. After computing prefix sums, you iterate through the houses and accumulate the required movement time based on prefix differences.

Recommended for interviews: Interviewers typically expect the prefix sum optimization. A brute force implementation shows you understand the problem mechanics, but recognizing repeated range calculations and replacing them with a prefix array demonstrates stronger algorithmic intuition. The optimal solution runs in O(n) time with O(n) space and scales efficiently for large inputs.

Solutions for this problem are being prepared.

Try solving it yourself

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Direct Range SummationO(n^2)O(1)Useful for understanding the baseline logic or when the array size is very small.
Prefix Sum OptimizationO(n)O(n)Best choice for large inputs where repeated range-sum calculations must be avoided.

Video Solution

leetcode 3540 Minimum Time to Visit All Houses | partial sums • Code-Yao • 378 views views

Frequently Asked Questions

Is Minimum Time to Visit All Houses easy or hard?
Minimum Time to Visit All Houses is generally classified as a Medium problem. The implementation is straightforward once you recognize that repeated range calculations can be optimized using a prefix sum technique.
Minimum Time to Visit All Houses Python/Java solution
Most implementations compute a prefix sum array first and then iterate through the houses while calculating travel time using prefix differences. The logic is identical across Python, Java, C++, and Go with only syntax differences.
How to solve Minimum Time to Visit All Houses in O(n)?
Build a prefix sum array where prefix[i] stores the total travel time from the first house up to index i. The travel time between any two houses can then be computed as prefix[r] - prefix[l]. This removes repeated range summations and allows the algorithm to finish in linear time.
What is the best approach for Minimum Time to Visit All Houses?
The prefix sum approach is the most efficient solution. Precompute cumulative travel times so the cost between any two houses can be calculated in O(1). This reduces the overall complexity to O(n) time with O(n) extra space.
Is Minimum Time to Visit All Houses asked at Google/Amazon/Meta?
Problems involving prefix sums and cumulative array calculations frequently appear in interviews at companies like Amazon, Google, and Meta. Variations typically test your ability to optimize repeated range computations using prefix sums.
What data structure is used in Minimum Time to Visit All Houses?
The core data structure is an array combined with a prefix sum array. The prefix array stores cumulative values so range costs can be calculated instantly without iterating through the segment each time.
What is the time complexity of Minimum Time to Visit All Houses?
The optimal prefix sum solution runs in O(n) time because the algorithm performs a single pass to build cumulative sums and another pass to compute the total travel time. Space complexity is O(n) for storing the prefix array.

Ready to solve this problem?

Practice Minimum Time to Visit All Houses with our built-in code editor and test cases.

Practice on FleetCode