LeetCode Entry

1460. Make Two Arrays Equal by Reversing Subarrays

03.08.2024 easy 2024 kotlin rust

Can arr transform to target by rotating subarrays?

1460. Make Two Arrays Equal by Reversing Subarrays easy blog post substack youtube 2024-08-03_09-07_1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/691

Problem TLDR

Can arr transform to target by rotating subarrays? #easy

Intuition

By swapping every subarray we can move any position to any other position, effectively sorting the array as we want. So, compare the sorted arrays or compare the numbers’ frequencies.

Approach

Let’s implement both variants.

Complexity

  • Time complexity: \(O(n)\) and \(O(nlogn)\) for sorting

  • Space complexity: \(O(n)\) and \(O(1)\) for sorting

Code


    fun canBeEqual(target: IntArray, arr: IntArray) =
        target.groupBy { it } == arr.groupBy { it }


    pub fn can_be_equal(mut target: Vec<i32>, mut arr: Vec<i32>) -> bool {
        target.sort_unstable(); arr.sort_unstable(); target == arr
    }