Minimum Number of Moves to Seat Everyone - Problem
Classroom Seating Challenge
Imagine a classroom scenario where
seats: An array where
students: An array where
Your task: Help each student reach a seat with the minimum total number of moves. Each move allows a student to shift their position by exactly 1 unit (left or right).
Goal: Return the minimum number of moves required so that every student occupies exactly one seat, with no two students sharing the same seat.
Note: Multiple students or seats can initially be at the same position.
Imagine a classroom scenario where
n students need to find their assigned seats. You're given two arrays:seats: An array where
seats[i] represents the position of the i-th available seatstudents: An array where
students[j] represents the current position of the j-th studentYour task: Help each student reach a seat with the minimum total number of moves. Each move allows a student to shift their position by exactly 1 unit (left or right).
Goal: Return the minimum number of moves required so that every student occupies exactly one seat, with no two students sharing the same seat.
Note: Multiple students or seats can initially be at the same position.
Input & Output
example_1.py β Basic Case
$
Input:
seats = [3,1,5], students = [2,7,4]
βΊ
Output:
4
π‘ Note:
After sorting: seats=[1,3,5], students=[2,4,7]. Optimal pairing: student at 2βseat 1 (1 move), student at 4βseat 3 (1 move), student at 7βseat 5 (2 moves). Total: 4 moves.
example_2.py β Perfect Match
$
Input:
seats = [4,1,5,9], students = [1,3,2,6]
βΊ
Output:
7
π‘ Note:
After sorting: seats=[1,4,5,9], students=[1,2,3,6]. Distances: |1-1|+|2-4|+|3-5|+|6-9| = 0+2+2+3 = 7 moves total.
example_3.py β Same Positions
$
Input:
seats = [2,2,6,6], students = [1,3,2,6]
βΊ
Output:
4
π‘ Note:
After sorting: seats=[2,2,6,6], students=[1,2,3,6]. Distances: |1-2|+|2-2|+|3-6|+|6-6| = 1+0+3+0 = 4 moves total.
Constraints
- n == seats.length == students.length
- 1 β€ n β€ 100
- 1 β€ seats[i], students[j] β€ 100
- All positions are positive integers
- Multiple seats or students can be at the same initial position
Visualization
Tap to expand
Understanding the Visualization
1
Initial Chaos
Students and seats are in random positions - we need to find the best matching strategy
2
Sort Students
Arrange students by their current positions from left to right
3
Sort Seats
Arrange available seats by their positions from left to right
4
Optimal Pairing
Match each student with the corresponding seat by index - no crossing paths needed
Key Takeaway
π― Key Insight: The optimal strategy is to sort both arrays and pair elements by index. This greedy approach works because any crossing assignments would only increase total distance - like organizing people by height for maximum efficiency!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code