Leetcode 1460. Make Two Arrays Equal by Reversing Subarrays
Given two integer arrays target
and arr
, you can perform the following operation on arr
any number of times:
arr
and reverse it.Return True
if you can make arr
equal to target
, or False
otherwise.
target
and arr
always the same?
target
and arr
will be in the range [1, 1000]
.Reversing subarrays implies that we can rearrange the elements in arr
in any order. Therefore, the problem reduces to checking if both arrays contain the same elements with the same frequencies.
The easiest way to do this is to:
If the sorted arrays are identical, then arr
can be transformed into target
by a series of subarray reversals. If not, it cannot.
So, the overall time complexity is (O(n \log n)), which is efficient for the given constraints.
#include <vector>
#include <algorithm>
class Solution {
public:
bool canBeEqual(std::vector<int>& target, std::vector<int>& arr) {
// Sort both target and arr
std::sort(target.begin(), target.end());
std::sort(arr.begin(), arr.end());
// Compare the sorted arrays
return target == arr;
}
};
target
and arr
.==
operator to check if the sorted arrays are identical.This method ensures that we are checking if both arrays can be rearranged to be the same, which is the core requirement of the problem.
This solution is efficient and leverages sorting to simplify the problem of checking for equality after potentially unlimited subarray reversals.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?