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:
|
|
Explanation
- We are using two dictionaries,
target_count
andarr_count
, to store the count of each value intarget
andarr
, respectively. - We then compare these two dictionaries. If they are the same, it means that
arr
can be made equal totarget
by reversals, so we returntrue
. Otherwise, we returnfalse
.