Leetcode 2037: Minimum Number of Moves to Seat Everyone

grid47
grid47
Exploring patterns and algorithms
Apr 17, 2024 5 min read

You are given two arrays: one representing the available seats in a row and the other representing the students who need to be seated. Each element in the arrays corresponds to a student’s desired seat or the position of an available seat. The task is to determine the minimum number of moves required to seat all students. A move consists of moving a student from one seat to another.
Problem
Approach
Steps
Complexity
Input: The input consists of two arrays: 'seats' representing the available seat positions and 'students' representing the students' desired seat positions.
Example: [[3, 1, 5, 2], [2, 5, 1, 3]]
Constraints:
• 1 <= seats.length, students.length <= 100
• 1 <= seats[i], students[i] <= 1000
Output: Return the minimum number of moves required to seat all students in the correct seats.
Example: 6
Constraints:
• The solution must be efficient, ideally O(n log n), due to the sorting step.
Goal: The goal is to calculate the minimum number of moves required to seat all students by sorting both arrays and matching each student's desired position with the available seats.
Steps:
• 1. Sort the 'seats' and 'students' arrays.
• 2. For each student, calculate the absolute difference between the student's desired seat and the actual seat.
• 3. Sum up the differences to get the total number of moves.
Goal: The constraints ensure that the input sizes are manageable, and the solution needs to be efficient with respect to time complexity.
Steps:
• 1 <= seats.length, students.length <= 100
• 1 <= seats[i], students[i] <= 1000
Assumptions:
• Each student must sit in one seat, and each seat can only be occupied by one student.
• The seating order does not matter, only the minimum number of moves to achieve the seating arrangement.
Input: [[3, 1, 5, 2], [2, 5, 1, 3]]
Explanation: In this case, we sort the seats and students arrays: [1, 2, 3, 5] for seats and [1, 2, 3, 5] for students. The absolute differences are: |1-1| + |2-2| + |3-3| + |5-5| = 0 + 0 + 0 + 0 = 6 moves.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus