Leetcode Problem 2037: Minimum Number of Moves to Seat Everyone
You are given two arrays seats
and students
of equal length representing the positions of seats and students, respectively. The seats
array is sorted in non-decreasing order. The task is to find the minimum number of moves required to seat every student in a seat such that each student moves to exactly one seat and each seat is occupied. One move consists of changing the position of a student by 1 unit to the left or right.
seats = [3, 1, 5]
students = [2, 7, 4]
n == seats.length == students.length
1 <= n <= 100
1 <= seats[i], students[i] <= 100
seats
and students
lies between 1 and 100.def minMovesToSeat(seats, students):
seats.sort()
students.sort()
# Calculate the total moves required
total_moves = 0
for i in range(len(seats)):
total_moves += abs(seats[i] - students[i])
return total_moves
# Test case
seats = [3, 1, 5]
students = [2, 7, 4]
print(minMovesToSeat(seats, students)) # Output: 4
The primary operations that determine the time complexity of this solution are:
seats
array: O(n log n)students
array: O(n log n)Therefore, the total time complexity is: [ \mathcal{O}(n \log n) + \mathcal{O}(n \log n) + \mathcal{O}(n) = \mathcal{O}(n \log n) ]
Given the constraints, this solution is efficient and suitable.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?