1725. Seat Everyone
A school hall has n seats placed along a corridor, where seats[i] is the position of seat i; several seats may share a position. There are also n students standing at the positions in students, and positions may repeat as well. Every student must end up on a different seat.
In one step a student moves one unit left or right along the corridor. Return the minimum total number of steps over all students as a long. Pairing the sorted students with the sorted seats is optimal, because swapping any crossing pair never helps. This runs in O(n log n) time and O(n) space for the sorted copies.
Example 1
- Input:
- seats = [3,1,5], students = [2,7,4]
- Output:
- 4
- Explanation:
Sorted seats 1, 3, 5 against sorted students 2, 4, 7 cost 1 + 1 + 2 = 4.
Example 2
- Input:
- seats = [4,4], students = [4,4]
- Output:
- 0
- Explanation:
Everybody is already standing at a seat, so the cost is 0.
Example 3
- Input:
- seats = [2,2,6], students = [1,3,9]
- Output:
- 5
- Explanation:
Two seats share position 2; the sorted pairing costs 1 + 1 + 3 = 5.
Constraints
1 ≤ n ≤ 1000
seats.length == students.length
1 ≤ seats[i], students[i] ≤ 109
Several seats may share a position.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)