Minimum Number of Moves to Seat Everyone - Problem
There are n available seats and n students standing in a room. You are given an array seats of length n, where seats[i] is the position of the ith seat. You are also given the array students of length n, where students[j] is the position of the jth student.
You may perform the following move any number of times:
- Increase or decrease the position of the ith student by 1 (i.e., moving the ith student from position
xtox + 1orx - 1)
Return the minimum number of moves required to move each student to a seat such that no two students are in the same seat.
Note: There may be multiple seats or students in the same position at the beginning.
Input & Output
Example 1 — Basic Case
$
Input:
seats = [3,1,5], students = [2,7,4]
›
Output:
4
💡 Note:
After sorting: students=[2,4,7], seats=[1,3,5]. Moves: |2-1|+|4-3|+|7-5| = 1+1+2 = 4
Example 2 — Same Positions
$
Input:
seats = [4,1,5,9], students = [1,3,2,6]
›
Output:
7
💡 Note:
After sorting: students=[1,2,3,6], seats=[1,4,5,9]. Moves: |1-1|+|2-4|+|3-5|+|6-9| = 0+2+2+3 = 7
Example 3 — Minimal Case
$
Input:
seats = [2,2,6,6], students = [1,3,2,6]
›
Output:
4
💡 Note:
After sorting: students=[1,2,3,6], seats=[2,2,6,6]. Moves: |1-2|+|2-2|+|3-6|+|6-6| = 1+0+3+0 = 4
Constraints
- n == seats.length == students.length
- 1 ≤ n ≤ 100
- 1 ≤ seats[i], students[j] ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input
Students at positions [3,1,5], seats at [2,7,4]
2
Process
Sort both arrays and pair optimally
3
Output
Minimum total moves = 4
Key Takeaway
🎯 Key Insight: Sorting both arrays and pairing corresponding positions minimizes total Manhattan distance
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code