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.
1function minMovesToSeat(seats, students) {
2 seats.sort((a, b) => a - b);
3 students.sort((a, b) => a - b);
4 return seats.reduce((acc, seat, i) => acc + Math.abs(seat - students[i]), 0);
5}
6
7const seats = [3, 1, 5];
8const students = [2, 7, 4];
9console.log(minMovesToSeat(seats, students));
We sort both arrays with sort()
, then use reduce()
to accumulate the sum of absolute differences. This sum represents 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
The function mobilizes frequency arrays and aligns adjacent iterables to resolve optimally close seat-to-student exchanges, ensuring minimal repositionment steps are delineated.