Sponsored
Sponsored
This approach leverages the property that reversing subarrays can reorder elements but will not affect the element counts. Thus, if the sorted versions of the arrays are the same, then the arrays can be made equal.
Time complexity: O(n log n) due to sorting.
Space complexity: O(1) for in-place sort.
1import java.util.Arrays;
2
3class Solution {
4 public boolean canBeEqual(int[] target, int[] arr) {
5 Arrays.sort(target);
6 Arrays.sort(arr);
7 return Arrays.equals(target, arr);
8 }
9}
The Java solution uses Arrays.sort() to sort both arrays and Arrays.equals() to compare them.
Instead of sorting, we can simply count the occurrences of each element in both arrays. If the frequency distributions are the same, the arrays can be made equal.
Time complexity: O(n) for a single pass through the arrays.
Space complexity: O(1) as the frequency array size is constant.
1
Python uses the Counter class from the collections module to easily tally frequencies and compare them directly.