MediumArrayPrefix SumUpdated Sep 2026

3919. Minimum Cost to Move Between Indices

Asked at Visa

Difficulty

Medium

Time

O(n + q)

Space

O(n)

Pattern

Array

Companies

1

Problem

You get an array nums that is strictly increasing (every value is bigger than the one before it). You also get a list of queries; each query is a pair of indices [l, r].

From any index x you have two kinds of moves. First, you may jump to any index y and pay abs(nums[x] - nums[y]). Second, you may step to closest(x) and pay a flat cost of 1. Here closest(x) means the neighbor of x (index x-1 or x+1) whose value is nearest to nums[x]. If both neighbors are equally near, pick the smaller index. At the two ends there is only one neighbor, so that one is closest.

For each query, find the minimum total cost to travel from index l to index r. Return an array with one answer per query, in the same order.

Two kinds of moves

nums-5-23012closest(0)closest(0) = 1 because |-2 - (-5)| = 3 is the onlyneighborjump to y: cost |nums[x] - nums[y]|step to closest(x): cost 1The 1-cost step is the only way to beat the plainvalue gap.
From index 0 you can jump anywhere at the value gap, or step to closest(0) = 1 for just 1.

Constraints

  • ●2 <= nums.length <= 10^5
  • ●-10^9 <= nums[i] <= 10^9
  • ●nums is strictly increasing
  • ●1 <= queries.length <= 10^5
  • ●queries[i] = [li, ri]
  • ●0 <= li, ri < nums.length

Examples

Example 1
Inputnums = [-5,-2,3], queries = [[0,2],[2,0],[1,2]]
Output[6,2,5]
Whyclosest is [1,0,1]. For [0,2] we go 0→1 for cost 1, then 1→2 for cost |-2-3| = 5, total 6. For [2,0] we go 2→1 and 1→0, both closest moves, so 1+1 = 2. For [1,2] the direct jump costs 5, which beats any detour.
Example 2
Inputnums = [0,2,3,9], queries = [[3,0],[1,2],[2,0]]
Output[4,1,3]
Whyclosest is [1,2,1,2]. For [3,0] we go 3→2 (cost 1), 2→1 (cost 1), then 1→0 (cost |2-0| = 2), total 4. For [1,2] the closest move costs 1. For [2,0] we go 2→1 for 1, then 1→0 for 2, total 3.

Asked At

1 companies
CompanyDifficulty
VisaMediumView all Visa questions →

How to Think About It

1

Because nums is strictly increasing, a direct jump from l to r costs the same as walking every adjacent step at full price: nums[r] - nums[l].

2

So the only real saving is the 1-cost "closest" step. Walking one index at a time lets you use a 1-cost step whenever the neighbor you are heading to is the current index's closest.

3

Key insight: moving right from i to i + 1 costs 1 if closest(i) == i + 1, otherwise nums[i+1] - nums[i]. Moving left from i to i - 1 costs 1 if closest(i) == i - 1, otherwise the gap. Since every gap is at least 1, walking step by step is never worse than jumping.

4

Build two prefix-sum arrays — rightward step costs and leftward step costs — and answer each query by a subtraction.

5

Walkthrough for nums = [-5,-2,3]: closest = [1,0,1]. Right steps: 0->1 costs 1 (closest), 1->2 costs 5. Left steps: 2->1 costs 1, 1->0 costs 1. So 0->2 = 6, 2->0 = 2, 1->2 = 5.

Optimal Approach

Step 1: Compute closest(i): the only neighbor at the ends; otherwise the neighbor with the smaller gap, choosing the left one on ties.
Step 2: right[i+1] = right[i] + (1 if closest(i) == i+1 else nums[i+1] - nums[i]).
Step 3: left[i+1] = left[i] + (1 if closest(i+1) == i else nums[i+1] - nums[i]) — the cost of stepping from i+1 down to i.
Step 4: For a query (l, r): if l <= r, answer right[r] - right[l]; else left[l] - left[r].

Time: O(n + q). Space: O(n).

Walk one index at a time

numscost 1-5-230120→1: closest(0) = 1, so this step costs 1numscost 5-5-230121→2: closest(1) = 0, so we pay the full gap |-2-3| = 5right[i+1] = right[i] + (1 if closest(i)==i+1 else gap)left[i+1] = left[i] + (1 if closest(i+1)==i else gap)l <= r: right[r] - right[l]l > r: left[l] - left[r]
Each adjacent step is cheap exactly when the neighbor is that index's closest, so prefix sums give every answer in O(1).
ComplexityTime O(n + q)Space O(n)We precompute two prefix-sum arrays in one pass over nums, then each of the q queries is answered with a single subtraction.

What Trips People Up in Real Interviews

1

Running a shortest-path search per query. With 10^5 queries that is far too slow — prove that step-by-step walking is optimal first.

2

Using a single prefix array for both directions. closest is not symmetric, so the leftward and rightward step costs differ.

3

Breaking ties toward the right neighbor. The statement picks the smaller index on ties.

4

Overflow in C++/Java: gaps reach 2 * 10^9 and sums reach 10^14, so use 64-bit prefix sums.

Solution Code

O(n + q) time
def minCost(nums, queries):
    n = len(nums)

    def closest(i):
        if i == 0:
            return 1
        if i == n - 1:
            return n - 2
        return i - 1 if nums[i] - nums[i - 1] <= nums[i + 1] - nums[i] else i + 1

    right = [0] * n
    left = [0] * n
    for i in range(n - 1):
        gap = nums[i + 1] - nums[i]
        right[i + 1] = right[i] + (1 if closest(i) == i + 1 else gap)
        left[i + 1] = left[i] + (1 if closest(i + 1) == i else gap)
    res = []
    for l, r in queries:
        if l <= r:
            res.append(right[r] - right[l])
        else:
            res.append(left[l] - left[r])
    return res

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Minimum Cost to Move Between Indices problem?

Minimum Cost to Move Between Indices gives you a strictly increasing array. From index `x` you can jump to any index `y` for `|nums[x] - nums[y]|`, or step to `closest(x)` — the adjacent index with the smaller value gap — for a flat cost of 1. Answer many queries for the cheapest route from `l` to `r`. Once you see that the best route never skips an index, prefix sums answer each query in `O(1)`.

How do you solve Minimum Cost to Move Between Indices?

The optimal approach runs in O(n + q) time and O(n) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Minimum Cost to Move Between Indices?

Minimum Cost to Move Between Indices is asked at Visa. It is a medium difficulty problem.

What are common mistakes on Minimum Cost to Move Between Indices?
  • Running a shortest-path search per query. With `10^5` queries that is far too slow — prove that step-by-step walking is optimal first.
  • Using a single prefix array for both directions. `closest` is not symmetric, so the leftward and rightward step costs differ.
  • Breaking ties toward the right neighbor. The statement picks the smaller index on ties.
  • Overflow in C++/Java: gaps reach `2 * 10^9` and sums reach `10^14`, so use 64-bit prefix sums.