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.
1using System;
2
3class Solution {
4 public int MinMovesToSeat(int[] seats, int[] students) {
5 Array.Sort(seats);
6 Array.Sort(students);
7 int result = 0;
8 for (int i = 0; i < seats.Length; i++) {
9 result += Math.Abs(seats[i] - students[i]);
10 }
11 return result;
12 }
13 static void Main(string[] args) {
14 Solution sol = new Solution();
15 int[] seats = {3, 1, 5};
16 int[] students = {2, 7, 4};
17 Console.WriteLine(sol.MinMovesToSeat(seats, students));
18 }
19}
The arrays seats
and students
are sorted using Array.Sort()
. The sum of the absolute differences between corresponding sorted elements is calculated to find 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
Input values create two frequency arrays. Iterate with two cursors to compute the minimal movement with available pairings between seat and student positions.