EASY Approach || Beginners ||Full explanation.
\n\nConsider the following scenario:\n\n- seats array: [1, 4, 5] (represents available seats with positions 1, 4, and 5)\n- students array: [3, 2, 6] (represent
\n\nConsider the following scenario:\n\n- `seats` array: [1, 4, 5] (represents available seats with positions 1, 4, and 5)\n- `students` array: [3, 2, 6] (represents student positions that need to be assigned to seats)\n\n**Explanation with Table:**\n\n| Step | Description | Code |\n|---|---|---|\n| 1 (Optional) | Sort `seats` and `students` (for efficiency) | `Arrays.sort(seats);`<br> `Arrays.sort(students);` |\n| 2 | Initialize `ans` for total moves | `int ans = 0;` |\n| 3 | Iterate through student-seat pairs | `for(int i=0; i<seats.length; i++){ ... }` |\n| 4 | Calculate moves for each pair | `ans += Math.abs(students[i] - seats[i]);` |\n\n**Breakdown:**\n\n1. **Sorting (Optional):** As mentioned earlier, sorting might not be essential but simplifies the logic. We\'ll skip sorting for this example.\n\n2. **Iteration and Move Calculation:**\n\n   - The `for` loop iterates through each student-seat pair using the index `i`.\n\n   - In this example:\n     - `i=0`: Student at position `students[0] = 3` needs a seat. The corresponding seat at index `i` is `seats[0] = 1`. The difference (`Math.abs(3-1)`) is 2, representing the number of moves needed for this student.\n     - `i=1`: Student at position `students[1] = 2` needs a seat. The corresponding seat is `seats[1] = 4`. The difference (`Math.abs(2-4)`) is 2, representing the moves for this student.\n     - `i=2`: Student at position `students[2] = 6` needs a seat. The corresponding seat is `seats[2] = 5`. The difference (`Math.abs(6-5)`) is 1, representing the moves for this student.\n\n   - With each iteration, the absolute difference between student and seat positions is added to the `ans` variable, accumulating the total moves.\n\n3. **Return:**\n\n   - After iterating through all student-seat pairs, `ans` will hold the total number of moves required (5 in this case).\n\n**Overall:**\n\nBy iterating through student-seat pairs and calculating the absolute difference in positions, the code efficiently determines the minimum number of moves needed to seat all students.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\n    public int minMovesToSeat(int[] seats, int[] students) {\n        Arrays.sort(seats);\n        Arrays.sort(students);\n        int ans=0;\n        for(int i=0;i<seats.length;i++){\n            ans+=Math.abs(students[i]-seats[i]);\n        }\n        return ans;\n    }\n}\n```
['Sorting', 'Java']