Minimum Number of Moves to Seat Everyone

easy array sorting

Problem

There are n seats and n students. You are given two arrays seats and students of length n where seats[i] is the position of the i-th seat and students[j] is the position of the j-th student. You may move any student by 1 unit at a time. Return the minimum number of moves required so that every student is in a distinct seat.

Inputseats = [3, 1, 5], students = [2, 7, 4]
Output4
Sort to seats=[1,3,5], students=[2,4,7]. Diffs |1−2|+|3−4|+|5−7| = 1+1+2 = 4.

def min_moves_to_seat(seats, students):
    seats.sort()
    students.sort()
    total = 0
    for i in range(len(seats)):
        total += abs(seats[i] - students[i])
    return total
function minMovesToSeat(seats, students) {
  seats.sort((a, b) => a - b);
  students.sort((a, b) => a - b);
  let total = 0;
  for (let i = 0; i < seats.length; i++) {
    total += Math.abs(seats[i] - students[i]);
  }
  return total;
}
class Solution {
    public int minMovesToSeat(int[] seats, int[] students) {
        Arrays.sort(seats);
        Arrays.sort(students);
        int total = 0;
        for (int i = 0; i < seats.length; i++) {
            total += Math.abs(seats[i] - students[i]);
        }
        return total;
    }
}
int minMovesToSeat(vector<int>& seats, vector<int>& students) {
    sort(seats.begin(), seats.end());
    sort(students.begin(), students.end());
    int total = 0;
    for (int i = 0; i < (int)seats.size(); i++) {
        total += abs(seats[i] - students[i]);
    }
    return total;
}
Time: O(n log n) Space: O(1)