#2037

Minimum Number of Moves to Seat Everyone

Easy
ArrayGreedySortingCounting SortGreedySortingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

By sorting both the seats and students arrays, we can match each student to the closest available seat in a greedy manner. This minimizes the total distance moved by each student.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort both the seats and students arrays.
  2. 2Step 2: Initialize a variable to keep track of total moves.
  3. 3Step 3: Iterate through both arrays and calculate the total moves required to seat each student in the corresponding seat.
solution.py9 lines
1# Full working Python code
2
3def minMovesToSeat(seats, students):
4    seats.sort()
5    students.sort()
6    moves = 0
7    for i in range(len(seats)):
8        moves += abs(seats[i] - students[i])
9    return moves

Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) since we are using a constant amount of extra space.

  • 1Sorting helps in minimizing the distance moved by aligning students and seats.
  • 2Greedy approach works effectively when the problem requires minimizing total costs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.