Minimum Number of Moves to Seat Everyone
There are n seats and n students in a room. Each seat and student has a position on a number line. A move consists of moving a student by 1 position left or right. Find the minimum number of moves required to seat every student in a distinct seat.
Sort both arrays. The optimal assignment pairs the i-th smallest seat with the i-th smallest student. Sum the absolute differences between corresponding positions after sorting. This works due to the rearrangement inequality.
Time is O(n log n) for sorting, O(n) for the sum calculation. Space is O(1). Edge cases include a single student (return absolute difference), already matched positions (return 0), and large gaps between seats and students.
The pairing strategy of matching sorted positions minimizes total absolute distance because crossing pairs would only increase the total distance. This is formalized by the rearrangement inequality, which states that the sum of absolute differences is minimized when both sequences are sorted in the same order.
This problem illustrates how sorting enables optimal matching between two sets of points on a line, a pattern that appears in many assignment and scheduling problems.
Example Input & Output
Match: 1-2, 3-4, 5-7. Moves: 1+1+2=4.
5-5=0, 1-5=4. Total=4.
Single student moves 4.
Already matched.
Moves: 1-1=0, 3-4=1, 2-5=3, 6-9=3. Total=7.
Algorithm Flow

Solution Approach
Sort both arrays, sum absolute differences at each index.
Time O(n log n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int solution(int[] seats, int[] students) {
Arrays.sort(seats);Arrays.sort(students);
int m=0;
for (int i=0;i<seats.length;i++) m+=Math.abs(seats[i]-students[i]);
return m;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
