Make Two Arrays Equal by Reversing Subarrays

Here’s a simple way to determine whether arr can be made equal to target by reversing any of its non-empty subarrays.

We don’t need to actually perform the reversals. Since a reversal doesn’t change the count of any particular value in the array, we can just compare the counts of the values in target and arr. If they are the same, then arr can be made equal to target by reversals.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
        # Create a dictionary to store the count of each value in target
        target_count = {}
        for num in target:
            target_count[num] = target_count.get(num, 0) + 1

        # Create a dictionary to store the count of each value in arr
        arr_count = {}
        for num in arr:
            arr_count[num] = arr_count.get(num, 0) + 1

        # Compare the counts of values in target and arr
        return target_count == arr_count

Explanation

  • We are using two dictionaries, target_count and arr_count, to store the count of each value in target and arr, respectively.
  • We then compare these two dictionaries. If they are the same, it means that arr can be made equal to target by reversals, so we return true. Otherwise, we return false.