FastPrepFastPrep
Problem Brief

Rearrange Students

OA
See Tiktok online assessment and hiring insights

In your school, two lines of students are formed A and B, with each line having exactly N students. The two lines of students will face each other. The Physical Education teacher wants the heights of all students standing across from each other to be equal. To do this, students may be swapped from one line to another. Any student in one line can be swapped with any student in the other line. Each swap counts as one operation, and each operation costs the minimum height in the swap. Reordering the students within one line has no cost. Determine the minimal cost to achieve the desired result. If it is impossible, return -1.

Function Description

Complete the function rearrangeStudents in the editor.

The function has the following parameters:

  1. int arrA[n]: the heights of the children in line A
  2. int arrB[n]: the heights of the children in line B

Returns

long: the minimal cost to rearrange the students or -1

1Example 1

Input
arrA = [4, 2, 2, 2], arrB = [1, 4, 1, 2]
Output
1
Explanation

If the arrays are sorted descending, then arrA=[4, 2, 2, 2] and arrB = [4, 2, 1, 1]. Swap a 2 in arrA with a 1 in arrB for a cost of min(1, 2) = 1. This is the only swap that must occur, so the answer is 1.

Constraints

Limits and guarantees your solution can rely on.

  • 1 <= n <= 2 x 10^5
  • 1 <= arrA[i], arrB[i] <= 10^9
public long rearrangeStudents(int[] arrA, int[] arrB) {
  // write your code here
}
Input

arrA

[4, 2, 2, 2]

arrB

[1, 4, 1, 2]

Output

1

Sign in to submit your solution.