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 x to x + 1 or x - 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
Minimum Moves to Seat Everyone INPUT Seats Array: 3 1 5 [0] [1] [2] Students Array: 2 7 4 [0] [1] [2] Number Line: 1 2 3 4 5 7 Seat Student ALGORITHM STEPS 1 Sort Both Arrays seats: [1,3,5] students: [2,4,7] 2 Match by Index Pair seat[i] with student[i] 3 Calculate Distances |seat[i] - student[i]| Pair 0: |1-2| = 1 Pair 1: |3-4| = 1 Pair 2: |5-7| = 2 Total: 1+1+2 = 4 4 Sum All Moves Return total distance FINAL RESULT After sorting and matching: 1 2 1 move 3 4 1 move 5 7 2 moves Output: 4 OK - Minimum moves All students seated No conflicts Key Insight: Sorting both arrays ensures optimal pairing. The greedy approach works because pairing the i-th smallest seat with the i-th smallest student minimizes total moves. Time: O(n log n) for sorting | Space: O(1) or O(n) depending on sort implementation TutorialsPoint - Minimum Number of Moves to Seat Everyone | Greedy Approach - Sort and Match
Asked in
Google 12 Amazon 8 Microsoft 6
28.1K Views
Medium Frequency
~15 min Avg. Time
850 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