Beats 100% of Users in Typescript
\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe first thought is to minimize the total number of moves required to seat stu
\n![Screenshot from 2024-06-14 00-14-18.png](https://assets.leetcode.com/users/images/52b7e49b-164c-4b35-9bb3-e22a40562601_1718313517.9623773.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe first thought is to minimize the total number of moves required to seat students by matching them to the closest available seats. By sorting both the seats and the students, we can pair each student to the nearest seat in a straightforward manner.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Sort the Arrays**: Begin by sorting both the `seats` and `students` arrays in non-decreasing order.\n2. **Calculate Moves**: Initialize a counter `moves` to zero. Iterate through the sorted arrays, and for each pair of seat and student, calculate the absolute difference between their positions and add it to `moves`.\n3. **Return Result**: Finally, return the total number of moves accumulated.\n\nThis approach ensures that each student is matched to the closest available seat, minimizing the total movement.\n\n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n  The time complexity is \\(O(n \\log n)\\) because sorting the arrays is the most time-consuming operation.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n  The space complexity is \\(O(1)\\) if we do not count the input and output as extra space, or \\(O(n)\\) if we do.\n\n# Code\n```javascript\nfunction minMovesToSeat(seats, students) {\n    let moves = 0;\n    seats.sort((a, b) => a - b);\n    students.sort((a, b) => a - b);\n    for (let i = 0; i < seats.length; i++) {\n        moves += Math.abs(seats[i] - students[i]);\n    }\n    return moves;\n};\n
['TypeScript', 'JavaScript']