Easy Sort and One Pass Solution with Dry Run⭐💯
Min Moves to Seat Students\n\n## Problem Statement\nGiven two arrays seats and students representing the positions of seats and students respectively, find the 
# Min Moves to Seat Students\n\n## Problem Statement\nGiven two arrays `seats` and `students` representing the positions of seats and students respectively, find the minimum number of moves required to seat all the students such that each student sits on a seat. A move is defined as moving a student from one seat to another seat.\n\n## Approach\n1. **Sorting**: Sort both the `seats` and `students` arrays. Sorting helps in minimizing the movement by ensuring that each student is assigned to the closest possible seat.\n2. **Calculate Moves**: Iterate through the sorted arrays and calculate the absolute difference between the corresponding elements of `seats` and `students`. Sum these differences to get the total number of moves.\n\n## Complexity\n- **Time Complexity**: The time complexity is \\(O(n \\log n)\\) due to the sorting step, where \\(n\\) is the number of seats (or students).\n- **Space Complexity**: The space complexity is \\(O(1)\\) (excluding the input space) since we are using a constant amount of extra space.\n\n## Solution\n```cpp\nclass Solution {\npublic:\n    int minMovesToSeat(vector<int>& seats, vector<int>& students) {\n        // Sort both seats and students arrays\n        sort(seats.begin(), seats.end());\n        sort(students.begin(), students.end());\n\n        int moves = 0;\n        // Calculate the total moves required\n        for (int i = 0; i < seats.size(); i++) {\n            moves += abs(students[i] - seats[i]);\n        }\n\n        return moves;\n    }\n};\n```\n\n## Explanation\n1. **Sorting Step**: By sorting both `seats` and `students`, we align the smallest seat with the smallest student, the second smallest with the second smallest, and so on. This ensures the minimal total movement.\n2. **Calculating Moves**: By iterating through the sorted arrays and summing up the absolute differences between the corresponding elements, we get the minimum total moves required to seat all students.\n\n## Example\nConsider the following example to illustrate the approach:\n```cpp\nvector<int> seats = {3, 1, 5};\nvector<int> students = {2, 7, 4};\n\n// After sorting\n// seats = [1, 3, 5]\n// students = [2, 4, 7]\n\n// Calculate moves\n// abs(1 - 2) + abs(3 - 4) + abs(5 - 7)\n// = 1 + 1 + 2\n// = 4\n\nSolution solution;\nint result = solution.minMovesToSeat(seats, students);\n// result should be 4\n
['Array', 'Greedy', 'Sorting', 'C++']