Problem
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.
Examples
Example 1:
| |
Example 2:
| |
Example 3:
| |
Solution
Method 1 - Using Frequency map
A key insight here is that since reversing subarrays can be done any number of times, the relative ordering of elements within arr can be entirely changed. Therefore, transforming arr into target is possible if and only if both arrays contain the exact same elements in the same frequencies.
Steps
- Count Element Frequencies:
- Count the frequency of each element in both
targetandarr.
- Count the frequency of each element in both
- Compare Counts:
- If the frequency of each element in both arrays is the same, then it is possible to transform
arrintotargetthrough reversing operations.
- If the frequency of each element in both arrays is the same, then it is possible to transform
Code
| |
Complexity
- ⏰ Time complexity:
O(n)wherenis number of elements intargetorarrarrays. - 🧺 Space complexity:
O(n)for storing values in frequency map