✅Beats 100% Sorting Method To Find Minimum Moves to Seat Students
Intuition\n\nThe problem requires finding the minimum number of moves needed to seat students such that each student sits in a designated seat. Each move consis
## Intuition\n\nThe problem requires finding the minimum number of moves needed to seat students such that each student sits in a designated seat. Each move consists of moving a student from one position to another. By sorting both the `seats` and `students` arrays, we can minimize the total number of moves needed by pairing each student with the closest available seat.\n\n## Approach\n\n1. **Sort the arrays:**\n   - Sort the `seats` array in ascending order.\n   - Sort the `students` array in ascending order.\n2. **Calculate moves:**\n   - Initialize `moves` to 0 to keep track of the total number of moves.\n   - Iterate through each index `i` of the arrays.\n   - For each pair `(seats[i], students[i])`, calculate the absolute difference `abs(seats[i] - students[i])` and add it to `moves`.\n3. **Return the result:**\n   - After processing all pairs, return the total number of moves.\n\n## Complexity\n\n**Time complexity:** O(n log n)\n- Sorting the `seats` and `students` arrays each takes O(n log n) time.\n- Iterating through the arrays to calculate the total number of moves takes O(n) time.\n- Thus, the overall time complexity is O(n log n).\n\n**Space complexity:** O(1)\n- The algorithm uses a constant amount of extra space beyond the input arrays, resulting in O(1) space complexity.\n\n## Step by Step Explanation\n\nLet\'s take the example from the problem statement:\n\n### Example\n\n- **Seats:** [3, 1, 5]\n- **Students:** [2, 7, 4]\n\n### Initial State\n\n| Seats | Students |\n|-------|----------|\n| 3     | 2        |\n| 1     | 7        |\n| 5     | 4        |\n\n### After Sorting\n\n| Seats | Students |\n|-------|----------|\n| 1     | 2        |\n| 3     | 4        |\n| 5     | 7        |\n\n### Calculate Moves\n\n| Seat | Student | Moves |\n|------|---------|-------|\n| 1    | 2       | 1     |\n| 3    | 4       | 1     |\n| 5    | 7       | 2     |\n\n**Total Moves:**  = 4\n\nThe total number of moves required is 4.\n\n# Code\n```\nclass Solution {\npublic:\n    int minMovesToSeat(vector<int>& seats, vector<int>& students) {\n        sort(seats.begin(),seats.end());\n        sort(students.begin(),students.end());\n        int moves = 0;\n\n        for(int i = 0 ; i < students.size() ; i++){\n            moves+= abs(seats[i] - students[i]);\n        }\n        return moves;\n\n    }\n};\n```
['Array', 'Sorting', 'C++']