Sponsored
Sponsored
This approach relies on sorting both the seats
and students
arrays. After sorting them, we pair the i-th seat with the i-th student. The sum of absolute differences between corresponding elements gives us the minimum number of moves required.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) since sorting is in-place.
1def min_moves_to_seat(seats, students):
2 seats.sort()
3 students.sort()
4 return sum(abs(s - st) for s, st in zip(seats, students))
5
6seats = [3, 1, 5]
7students = [2, 7, 4]
8print(min_moves_to_seat(seats, students))
Using sort()
for both lists, we zip them to calculate the sum of absolute differences between paired elements, which gives the minimum moves.
This approach involves creating frequency arrays or maps for both seats and students positions. Align students to seats by finding the closest available seat iteratively, simulating a greedy approach.
Time Complexity: O(n + m), where m is the range of possible positions (maximum 100).
Space Complexity: O(m) due to frequency arrays.
1#include <vector>
#include <algorithm>
int minMovesToSeat(std::vector<int>& seats, std::vector<int>& students) {
std::vector<int> seatCount(101, 0), studentCount(101, 0);
for (int seat : seats) seatCount[seat]++;
for (int student : students) studentCount[student]++;
int i = 0, j = 0, moves = 0;
while (i < 101 && j < 101) {
if (seatCount[i] > 0 && studentCount[j] > 0) {
int min_count = std::min(seatCount[i], studentCount[j]);
moves += abs(i - j) * min_count;
seatCount[i] -= min_count;
studentCount[j] -= min_count;
}
if (seatCount[i] == 0) i++;
if (studentCount[j] == 0) j++;
}
return moves;
}
int main() {
std::vector<int> seats = {3, 1, 5};
std::vector<int> students = {2, 7, 4};
std::cout << minMovesToSeat(seats, students) << std::endl;
return 0;
}
Create frequency counts for both seats and students. Utilize two iterators to link closest seat-student pairs while counting movements.