Minimum Number of Moves to Seat Everyone — LeetCode 2037 Python Solution
- Problem
- #2037
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
There are n availabe 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.
Example
- Input
- seats = [3,1,5], students = [2,7,4]
- Output
- 4
- Explanation
- The students are moved as follows:
Python solution
class Solution:
def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
seats.sort()
students.sort()
return sum(abs(a - b) for a, b in zip(seats, students))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\log n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2037. Minimum Number of Moves to Seat Everyone is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2037. Minimum Number of Moves to Seat Everyone?
- LeetCode 2037. Minimum Number of Moves to Seat Everyone is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2037. Minimum Number of Moves to Seat Everyone?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2037. Minimum Number of Moves to Seat Everyone?
- The Python solution on this page uses O(\log n) auxiliary space.
- What topics does LeetCode 2037. Minimum Number of Moves to Seat Everyone cover?
- LeetCode 2037. Minimum Number of Moves to Seat Everyone is tagged Greedy, Array, Counting Sort and Sorting on LeetCode.