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: forward =[1,4,4], backward =[4,1,2], queries =[1,2,0,2]Output: 12Explanation:
The path followed is0(0)→1(1)→2(5)→1(7)→0(8)→2(12).Note: The notation used isnode(total time),→ represents forward road, and → represents backward road.
Input: forward =[1,1,1,1], backward =[2,2,2,2], queries =[1,2,3,0]Output: 4Explanation:
The path travelled is0→1→2→3→0. Each step isin the forward direction and requires 1 second.
From any current house pos to a target q there are two simple choices: walk around the circle following the forward edges (clockwise) or follow the backward edges (counterclockwise). Precompute prefix sums for forward and for backward (in the form used below) so we can compute either route in O(1) per query. Sum the minimum of the two for each query while updating pos.
Build prefixF where prefixF[i] is distance from house 0 to house i following forward edges (with prefixF[0]=0 and prefixF[n]=totalForward).
Build prefixB where prefixB[i] equals sum of backward[1]..backward[i] (with prefixB[0]=0). Also compute sumB = sum(backward).
To get clockwise distance from pos to q: if q < pos we wrap and add prefixF[n], so cw = (q < pos ? prefixF[n] : 0) + prefixF[q] - prefixF[pos].
To get counterclockwise distance following backward edges from pos to q: if q > pos we wrap and add sumB, so ccw = (q > pos ? sumB : 0) + prefixB[pos] - prefixB[q].
For each query pick min(cw, ccw) and accumulate to ans, then set pos = q.
Edge cases and checks:
Arrays lengths match by constraint; queries[i] != queries[i+1] and queries[0] != 0 per constraints but algorithm works regardless.
⏰ Time complexity: O(n + m) where n is the number of houses and m is queries.length — building prefix sums takes O(n) and each query is handled in O(1).