Minimum Number of Moves to Seat Everyone

Approach

  1. Sort both the seats and students arrays: We will sort both arrays so that we can easily match the closest seat with a student.
  2. Calculate the moves required: For each student, we will calculate the absolute difference between the student’s position and the corresponding seat’s position. The absolute difference gives us the minimum number of moves required to move a student to a seat.
  3. Sum the moves: Finally, we’ll sum all the moves required for all students and return the result.

Code

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
    def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
        # Sort the seats and students
        seats.sort()
        students.sort()

        # Initialize the total moves required
        total_moves = 0

        # Iterate through the sorted seats and students
        for i in range(len(seats)):
            # Add the absolute difference between seat and student position to total_moves
            total_moves += abs(seats[i] - students[i])

        return total_moves

Explanation

  • By sorting both the seats and students, we make sure that we match each student with the closest available seat.
  • We use the absolute value of the difference between the seat’s position and the student’s position to calculate the minimum moves required for each student.
  • The final result is the sum of the minimum moves for all students.