#1460
Make Two Arrays Equal by Reversing Subarrays
EasyArrayHash TableSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal approach leverages sorting. If both arrays contain the same elements, regardless of order, they can be made equal by reversing subarrays. Sorting allows us to easily compare the contents of both arrays.
⚙️
Algorithm
3 steps- 1Step 1: Sort both target and arr.
- 2Step 2: Compare the sorted arrays element by element.
- 3Step 3: If all elements match, return true; otherwise, return false.
solution.py4 lines
1# Full working Python code
2
3def canMakeEqual(target, arr):
4 return sorted(target) == sorted(arr)ℹ
Complexity note: Sorting both arrays takes O(n log n) time, and the space complexity is O(n) due to the sorting operation.
- 1Both arrays must contain the same elements to be made equal.
- 2Sorting provides a quick way to check for equality of contents.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.