Skip to content

2037. Minimum Number of Moves to Seat Everyone 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int minMovesToSeat(vector<int>& seats, vector<int>& students) {
    int ans = 0;

    sort(begin(seats), end(seats));
    sort(begin(students), end(students));

    for (int i = 0; i < seats.size(); ++i)
      ans += abs(seats[i] - students[i]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int minMovesToSeat(int[] seats, int[] students) {
    int res = 0;

    Arrays.sort(seats);
    Arrays.sort(students);

    for (int i = 0; i < seats.length; ++i)
      res += Math.abs(seats[i] - students[i]);

    return res;
  }
}
1
2
3
class Solution:
  def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
    return sum(abs(seat - student) for seat, student in zip(sorted(seats), sorted(students)))