
Problem Statement
In a room, there are n
seats available and an equal number of n
students standing. Each seat and each student is positioned within this room. The task is to calculate the minimum number of single-step moves required to seat all the students such that each student occupies one seat. A move consists of increasing or decreasing a student's position by 1
. Additionally, no two students can share the same seat at the end. This problem provides us with two arrays: seats
, where seats[i]
indicates the position of the i-th
seat, and students
, where students[j]
marks the position of the j-th
student. The objective is to reposition the students with the minimal possible moves to ensure every student is seated without any overlaps, even if some seats or students start from the same position.
Examples
Example 1
Input:
seats = [3,1,5], students = [2,7,4]
Output:
4
Explanation:
The students are moved as follows: - The first student is moved from position 2 to position 1 using 1 move. - The second student is moved from position 7 to position 5 using 2 moves. - The third student is moved from position 4 to position 3 using 1 move. In total, 1 + 2 + 1 = 4 moves were used.
Example 2
Input:
seats = [4,1,5,9], students = [1,3,2,6]
Output:
7
Explanation:
The students are moved as follows: - The first student is not moved. - The second student is moved from position 3 to position 4 using 1 move. - The third student is moved from position 2 to position 5 using 3 moves. - The fourth student is moved from position 6 to position 9 using 3 moves. In total, 0 + 1 + 3 + 3 = 7 moves were used.
Example 3
Input:
seats = [2,2,6,6], students = [1,3,2,6]
Output:
4
Explanation:
Note that there are two seats at position 2 and two seats at position 6. The students are moved as follows: - The first student is moved from position 1 to position 2 using 1 move. - The second student is moved from position 3 to position 6 using 3 moves. - The third student is not moved. - The fourth student is not moved. In total, 1 + 3 + 0 + 0 = 4 moves were used.
Constraints
n == seats.length == students.length
1 <= n <= 100
1 <= seats[i], students[j] <= 100
Approach and Intuition
The problem at hand can be intuitively solved by trying to minimize the distance each student has to travel to find a seat. A logical approach to achieve this minimization is to sort both the seats
and students
arrays. By sorting both arrays, each student will ideally move towards the nearest available seat. When the arrays are sorted, the i-th
student will move to the i-th
seat. This pairing minimizes the total distance that all students need to move because each student is paired to the closest possible seat without any complex cross-matching.
Let's break down how this approach works using the provided examples:
Sort Both Arrays:
- Begin by sorting the
seats
andstudents
arrays. This will place the seats and students in ascending order of their positions.
- Begin by sorting the
Calculate the Moves:
- Iterate over the sorted arrays. For each student-seat pair (pairing the same indexed elements from both arrays), calculate the distance (or moves required) by finding the absolute difference between the student's position and the seat's position.
- Sum these calculated moves for all pairs to get the total minimum moves required.
For example, consider the third given scenario:
- Initial arrays are - Seats: [2,2,6,6], Students: [1,3,2,6]
- Sorted arrays become - Seats: [2,2,6,6], Students: [1,2,3,6]
- Minimum moves:
- Move student at position 1 to seat at position 2: 1 move
- Student at position 2 is already at the next seat: 0 moves
- Move student from position 3 to the next seat at position 6: 3 moves
- Student at position 6 does not move: 0 moves
- Total moves = 1 + 3 = 4
This example clearly illustrates how sorting helps in minimizing the movements by directly pairing each sorted student to a correspondingly sorted seat.
Solutions
- C++
- Java
- Python
class Solution {
public:
int seatStudents(vector<int>& seats, vector<int>& students) {
// Calculate the greatest position among seats and students
int maxPosition = max(getMaxPosition(seats), getMaxPosition(students));
// Differences array keeps track of seat and student disparity at positions
vector<int> positionDifferences(maxPosition, 0);
// Increment for each seat at a specific position
for (int seat : seats) {
positionDifferences[seat - 1]++;
}
// Decrement for each student at a specific position
for (int student : students) {
positionDifferences[student - 1]--;
}
// Accumulate the total moves required to seat all students
int totalMoves = 0, balance = 0;
for (int difference : positionDifferences) {
totalMoves += abs(balance);
balance += difference;
}
return totalMoves;
}
private:
int getMaxPosition(const vector<int>& data) {
int maxVal = 0;
for (int value : data) {
if (value > maxVal) {
maxVal = value;
}
}
return maxVal;
}
};
In the given C++ solution, the problem of seating students in the minimum number of moves is solved efficiently. Here's a summary of how the solution operates:
The solution defines a
Solution
class with two primary methods:seatStudents
for solving the problem and a helper methodgetMaxPosition
to find the maximum seat or student position.Inside
seatStudents
, it starts by determining the maximum position value among the seats and students using the helper method. This helps in creating an adequately sized vectorpositionDifferences
to track the difference in seat availability at each position.The function then iterates through the
seats
array, increasing the corresponding index in thepositionDifferences
array for each seat found. Following that, it decreases the count at each index in the samepositionDifferences
array for each student position.A running balance is maintained while iterating through
positionDifferences
to calculate how many moves are required to seat all students properly. The balance tracks the net position discrepancies between available seats and students, accumulating the absolute value of this running balance tototalMoves
.
This approach ensures that the total number of moves made to seat all students is minimized by directly resolving seat and student count imbalances across possible positions.
class Solution {
public int calculateMinimumMoves(int[] seatsArray, int[] studentsArray) {
int highestPosition = Math.max(getMaxValue(seatsArray), getMaxValue(studentsArray));
int[] countDifferences = new int[highestPosition];
for (int seat : seatsArray) {
countDifferences[seat - 1]++;
}
for (int student : studentsArray) {
countDifferences[student - 1]--;
}
int totalMoves = 0;
int unpaired = 0;
for (int diff : countDifferences) {
totalMoves += Math.abs(unpaired);
unpaired += diff;
}
return totalMoves;
}
private int getMaxValue(int[] values) {
int max = 0;
for (int value : values) {
if (value > max) {
max = value;
}
}
return max;
}
}
This Java solution addresses the problem of finding the minimum number of moves required to seat everyone by comparing two integer arrays: seatsArray
, representing seat positions, and studentsArray
, representing student positions.
The key steps involved in the solution are as follows:
- Calculate the highest seat or student position to define the range of position differences.
- Initialize an array
countDifferences
with a size equal to the highest position, used to record the imbalance between seats and students at each position. - Iterate through
seatsArray
and increment the corresponding index incountDifferences
for populated seats. - Iterate through
studentsArray
and decrement the corresponding index incountDifferences
for each student. - Calculate the total moves required to balance the differences:
- Initialize a counter
totalMoves
to accumulate the total moves necessary. - Use an intermediate variable
unpaired
to track the cumulative surplus or deficit of seats to students as you iterate throughcountDifferences
. - For each iteration, movements required are updated by adding the absolute value of
unpaired
tototalMoves
. - Update
unpaired
with the current difference fromcountDifferences
.
- Initialize a counter
The function getMaxValue
helps in determining the maximum value in an array, which is essential for properly sizing the countDifferences
array and avoiding indexing errors.
Following these steps effectively helps ensure that seat assignments require the minimal amount of movement, optimizing the process of seating every student.
class Solution:
def minMoves(self, seats: List[int], students: List[int]) -> int:
maximum_value = max(max(seats), max(students))
difference_counts = [0] * maximum_value
for seat in seats:
difference_counts[seat - 1] += 1
for student in students:
difference_counts[student - 1] -= 1
total_moves = 0
excess = 0
for diff in difference_counts:
total_moves += abs(excess)
excess += diff
return total_moves
The provided Python code solves the problem of finding the minimum number of moves required to seat everyone by matching seats
and students
. The core idea is to minimize the absolute distance seats have to move to accommodate students.
Here's how the solution works:
- Determine the
maximum_value
from the union of the maximum values in bothseats
andstudents
lists. - Create a list,
difference_counts
, initialized to zeroes with a length based onmaximum_value
. This list tracks the net availability of seats at each position. - Iterate over each
seat
and increment the corresponding index indifference_counts
, indicating that a seat is available. - Iterate over each
student
and decrement the corresponding index indifference_counts
, indicating a student needs a seat. - Initialize
total_moves
to zero, which will accumulate the total moves needed.excess
keeps track of the current imbalance of seats vs students as the algorithm assesses each position indifference_counts
. - Loop through each value in
difference_counts
, usingexcess
to adjust and track the net offset of students versus available seats and updatingtotal_moves
with the absolute value ofexcess
.
Finally, the function returns total_moves
, representing the minimum moves necessary to seat all students.
No comments yet.