Make Two Arrays Equal by Reversing Subarrays Problem
Description
LeetCode Problem 1460.
You are given two integer arrays of equal length target and arr. In one step, you can select any non-empty subarray of arr and reverse it. You are allowed to make any number of steps.
Return true if you can make arr equal to target or false otherwise.
Example 1:
Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
Explanation: You can follow the next steps to convert arr to target:
1- Reverse subarray [2,4,1], arr becomes [1,4,2,3]
2- Reverse subarray [4,2], arr becomes [1,2,4,3]
3- Reverse subarray [4,3], arr becomes [1,2,3,4]
There are multiple ways to convert arr to target, this is not the only way to do so.
Example 2:
Input: target = [7], arr = [7]
Output: true
Explanation: arr is equal to target without any reverses.
Example 3:
Input: target = [3,7,9], arr = [3,7,11]
Output: false
Explanation: arr does not have value 9 and it can never be converted to target.
Constraints:
target.length == arr.length1 <= target.length <= 10001 <= target[i] <= 10001 <= arr[i] <= 1000
Solution
Approach: Compare the Counts
Reversing a subarray of length 2 swaps two neighbours, and with enough neighbour swaps you can put the elements of an array in any order (that is all bubble sort does). So reversals can turn arr into any rearrangement of itself, and nothing else: a reversal never adds or removes a value.
That means arr can become target exactly when the two arrays hold the same values the same number of times. The values are at most 1000, so one count array is enough: add 1 for every value of target, subtract 1 for every value of arr, and check that every count ends at zero.
Duplicates are handled by the counts too: [1,1,2] and [1,2,2] contain the same distinct values, but the counts for 1 and 2 do not cancel, so the answer is false.
Complexity: O(n + V) time, where V = 1000 is the value range, and O(V) extra space for the counts. Sorting both arrays and comparing them also works in O(n log n).
class Solution:
def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
count = [0] * 1001 # values are in 1..1000
for a, b in zip(target, arr):
count[a] += 1
count[b] -= 1
return all(c == 0 for c in count)