LeetCode Entry

2037. Minimum Number of Moves to Seat Everyone

13.06.2024 easy 2024 kotlin rust

Sum of diffs of sorted students and seats

2037. Minimum Number of Moves to Seat Everyone easy blog post substack youtube 2024-06-13_06-42_1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/638

Problem TLDR

Sum of diffs of sorted students and seats #easy

Intuition

Deduce the intuition from the problem examples: the optimal solution is to take difference between sorted seats and students greedily.

Approach

Let’s use some languages iterators:

  • Kotlin: sorted, zip, sumOf
  • Rust: iter, zip, sum

Complexity

  • Time complexity: \(O(nlogn)\)

  • Space complexity: \(O(n)\) for Kotlin, O(1) for Rust solution

Code


    fun minMovesToSeat(seats: IntArray, students: IntArray) =
        seats.sorted().zip(students.sorted()).sumOf { (a, b) -> abs(a - b) }


    pub fn min_moves_to_seat(mut seats: Vec<i32>, mut students: Vec<i32>) -> i32 {
        seats.sort_unstable(); students.sort_unstable();
        seats.iter().zip(students).map(|(a, b)| (a - b).abs()).sum()
    }