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.
1import java.util.Arrays;
2
3public class Solution {
4 public int minMovesToSeat(int[] seats, int[] students) {
5 Arrays.sort(seats);
6 Arrays.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 public static void main(String[] args) {
14 Solution sol = new Solution();
15 int[] seats = {3, 1, 5};
16 int[] students = {2, 7, 4};
17 System.out.println(sol.minMovesToSeat(seats, students));
18 }
19}
We use Arrays.sort()
to sort both arrays, then calculate the sum of absolute differences between paired elements of the arrays, giving us the minimum moves required.
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
class Solution {
public int MinMovesToSeat(int[] seats, int[] students) {
int[] seatCount = new int[101];
int[] studentCount = new int[101];
foreach (int seat in seats) seatCount[seat]++;
foreach (int student in students) studentCount[student]++;
int i = 0, j = 0, moves = 0;
while (i < 101 && j < 101) {
if (seatCount[i] > 0 && studentCount[j] > 0) {
int minCount = Math.Min(seatCount[i], studentCount[j]);
moves += Math.Abs(i - j) * minCount;
seatCount[i] -= minCount;
studentCount[j] -= minCount;
}
if (seatCount[i] == 0) i++;
if (studentCount[j] == 0) j++;
}
return moves;
}
static void Main(string[] args) {
Solution sol = new Solution();
int[] seats = {3, 1, 5};
int[] students = {2, 7, 4};
Console.WriteLine(sol.MinMovesToSeat(seats, students));
}
}
Define seat and student position counts using integer arrays. Traverse with parallel iterators, reallocating students to minimize moves based on minimum position variance.