Magicsheet logo

Minimum Number of Moves to Seat Everyone

Easy
25%
Updated 8/1/2025

Minimum Number of Moves to Seat Everyone

1. What is this problem about?

The Minimum Number of Moves to Seat Everyone coding problem is a straightforward but essential challenge often used to introduce greedy optimization. You are given two arrays: seats and students. Each element in the arrays represents a position on a 1D line. You need to move each student to a seat such that no two students occupy the same seat, and the total distance moved by all students is minimized.

2. Why is this asked in interviews?

This question is a favorite for entry-level positions at companies like Microsoft, Amazon, and Google. It tests if a candidate understands the "assignment problem" in its simplest form. The interviewer wants to see if you can recognize that the optimal strategy is to pair the ii-th smallest student position with the ii-th smallest seat position.

3. Algorithmic pattern used

This problem follows the Array, Sorting, Counting Sort, Greedy interview pattern. The greedy insight is that sorting both arrays ensures that each student is moved to the "closest" available seat in a global sense. If you sort both seats and students, the total distance is simply the sum of abs(seats[i] - students[i]). While standard sorting (O(n log n)) is common, if the range of positions is small, Counting Sort (O(n)) can also be used.

4. Example explanation

Seats: [3, 1, 5] Students: [2, 7, 4]

  1. Sort Seats: [1, 3, 5]
  2. Sort Students: [2, 4, 7]
  3. Calculate distances:
    • Student 2 to Seat 1: |2 - 1| = 1
    • Student 4 to Seat 3: |4 - 3| = 1
    • Student 7 to Seat 5: |7 - 5| = 2 Total Moves: 1 + 1 + 2 = 4.

5. Common mistakes candidates make

The most common mistake is over-thinking the movement and trying to use a complex matching algorithm. Another error is failing to sort the arrays, which leads to a completely incorrect (and usually larger) result. Some candidates might also forget to use the absolute value when calculating the distance between a student and a seat.

6. Interview preparation tip

For "Easy" array problems, always ask yourself: "Does sorting the data make the greedy choice obvious?". Sorting is one of the most powerful pre-processing steps in interview coding and should be in your immediate toolkit for any optimization task.

Similar Questions