Minimum Number of Moves to Seat Everyone - Problem
Classroom Seating Challenge

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 seat
students: An array where students[j] represents the current position of the j-th student

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.

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
Optimal Seat Assignment StrategyBefore Sorting (Chaotic):Students: [2, 7, 4]Seats: [3, 1, 5]274315After Sorting (Organized):Students: [2, 4, 7]Seats: [1, 3, 5]247135Optimal Assignments:1 move1 move2 moves247135Total Minimum Moves: 1 + 1 + 2 = 4Key insight: Pairing sorted positions minimizes crossover!
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!
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
42.3K Views
Medium Frequency
~8 min Avg. Time
986 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen