OA Interview Problem: Minimum Total Lag to Connect Data Centers and Servers

18 Views
No Comments

An AWS client has brought servers and databases from data centers in different parts of the world for their application. For simplicity, let’s assume all the servers and data centers are located on a 1-dimensional line.

You have been given the task of optimizing the network connection.

Each data center must be connected to a server. The positions of data centers and servers are given in the form of arrays.

Any particular data center, center[i], can connect to any particular server destination[j].

The lag is defined as the distance between a data center at location x and a server destination at location y, i.e. |x - y|, the absolute difference between x and y. Determine the minimum lag to establish the entire network.

Example

There are n = 3 connections, the positions of data centers, center = [1, 2, 2], and the positions of the server destinations, destination = [5, 2, 4].

The most efficient deliveries are:

  • The center at location 1 makes the first connection to the server at location 2.
  • The center at location 2 makes the second connection to the server at location 4.
  • The center at location 2 makes the third connection to the server at location 5.

The minimum total lag is abs(1 - 2) + abs(2 - 4) + abs(2 - 5) = 1 + 2 + 3 = 6.

Function Description

Complete the function getMinDistance in the editor below.

getMinDistance has the following parameter(s):

  • int center[n]: the positions of data centers
  • int destination[n]: the positions of server destinations

Returns

  • long int: the minimum lag

Constraints

  • 1 <= n <= 10^5
  • 1 <= center[i], destination[i] <= 10^9

Sample Case 0

Input:

center = [3, 1, 6, 8, 9]
destination = [2, 3, 1, 7, 9]

Output:

5

Explanation:

You may create the connections as:

center = [1, 3, 6, 8, 9]
destination = [1, 2, 3, 7, 9]

Minimum total distance = abs(1 - 1) + abs(2 - 3) + abs(3 - 6) + abs(7 - 8) + abs(9 - 9) = 0 + 1 + 3 + 1 + 0 = 5.

Sample Case 1

Input:

center = [4, 6]
destination = [5, 5]

Output:

2

Explanation:

Minimum total distance = abs(5 - 4) + abs(5 - 6) = 1 + 1 = 2.

This problem reduces to minimizing the total absolute distance between two sets of points on a number line. The optimal approach is to sort both arrays and pair the smallest with the smallest, the second smallest with the second smallest, and so on. This greedy matching works because, in one dimension, sorted pairing minimizes the sum of absolute differences. The solution runs in O(n log n) time due to sorting and uses only simple linear traversal afterward.

END
 0