FastPrepOptimal Transfer

Optimal Transfer

Snowflake logoSnowflake● MediumINTERNOA
Learn

Problem statement

There are n servers indexed from 0 to n - 1. Their capacities are given in a strictly increasing integer array capacity.

The distance between servers x and y is |capacity[x] - capacity[y]|. Each server has a unique closest other server by this distance.

From a server x, you may make either type of move:

  • Move directly to any other server y for a cost of |capacity[x] - capacity[y]|.
  • Move to the closest server of x for a cost of 1.

The fixed-cost move is directed: if y is closest to x, x is not necessarily closest to y. You may use any number of moves, and a path costs the sum of its moves.

For every query i, find the minimum cost to travel from server fromServer[i] to server toServer[i]. Queries are independent and do not change any server. Return the costs in query order. When the starting and destination indices are equal, the empty path costs 0.

Function

minimumTransferCost(capacity: int[], fromServer: int[], toServer: int[]) → int[]

Examples

Example 1

capacity = [2,7,10]fromServer = [0,1,2]toServer = [2,2,1]return = [2,1,1]

The closest-server moves are 0 → 1, 1 → 2, and 2 → 1, each costing 1. The first query uses 0 → 1 → 2 for a total of 2; the other two each use one closest-server move.

Example 2

capacity = [1,4,9,15]fromServer = [0,3,1]toServer = [3,0,3]return = [12,3,11]

The closest-server moves are 0 → 1, 1 → 0, 2 → 1, and 3 → 2. Traveling right from 0 to 3 costs 1 + 5 + 6 = 12. Traveling left from 3 to 0 costs 1 + 1 + 1 = 3. The last query costs 5 + 6 = 11.

Example 3

capacity = [5,6,20]fromServer = [2,0,1]toServer = [0,1,1]return = [2,1,0]

The first query follows 2 → 1 → 0 for a cost of 2. Moving from 0 to 1 costs 1. The last query stays at server 1, so it costs 0.

Constraints

  • For this exercise, assume 2 <= capacity.length <= 100000 and 1 <= capacity[i] <= 10^9.
  • capacity is strictly increasing, and every server has exactly one closest other server. In particular, an interior server never has equal left and right capacity gaps.
  • For this exercise, assume 0 <= fromServer.length == toServer.length <= 100000.
  • Each query index lies in [0, capacity.length - 1].
  • All minimum costs fit in a signed 32-bit integer under these bounds.

More Snowflake problems

See Snowflake hiring insights
public int[] minimumTransferCost(int[] capacity, int[] fromServer, int[] toServer) {
    // Write your code here.
}
capacity[2,7,10]
fromServer[0,1,2]
toServer[2,2,1]
expected[2,1,1]
Checking account…