Make Two Arrays Equal by Reversing Subarrays - 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.

A subarray is a contiguous sequence of elements within an array.

Input & Output

Example 1 — Basic Case
$ Input: target = [1,2,3,4], arr = [2,4,1,3]
Output: true
💡 Note: Both arrays contain the same elements [1,2,3,4]. We can reverse subarrays to rearrange arr into target: reverse [2,4] to get [4,2,1,3], then reverse [4,2,1] to get [1,2,4,3], then reverse [4,3] to get [1,2,3,4].
Example 2 — Different Elements
$ Input: target = [7], arr = [1]
Output: false
💡 Note: The arrays contain different elements. arr has [1] while target has [7]. No amount of reversing can change the element values, only their positions.
Example 3 — Duplicate Elements
$ Input: target = [1,1,1,1,1], arr = [1,1,1,1,1]
Output: true
💡 Note: Both arrays contain the same elements with the same frequencies (five 1's). Since they're identical, they're already equal.

Constraints

  • target.length == arr.length
  • 1 ≤ target.length ≤ 1000
  • 1 ≤ target[i] ≤ 1000
  • 1 ≤ arr[i] ≤ 1000

Visualization

Tap to expand
Make Two Arrays Equal by Reversing Subarrays INPUT target array: 1 2 3 4 idx: 0 1 2 3 arr array: 2 4 1 3 idx: 0 1 2 3 Input Values: target = [1,2,3,4] arr = [2,4,1,3] Both arrays have length 4 ALGORITHM STEPS 1 Check Lengths Both must be same length 2 Sort Both Arrays Or count frequencies 3 Compare Check if sorted are equal 4 Return Result true if match, else false After Sorting: target sorted: 1 2 3 4 arr sorted: 1 2 3 4 = MATCH! FINAL RESULT true Output: return true Why true? Both arrays contain the same elements: {1,2,3,4} With unlimited reversals, any permutation achievable if elements match. OK Key Insight: Any subarray reversal is essentially a sequence of adjacent swaps. With unlimited reversals, you can rearrange arr into ANY permutation. Thus, arr can become target if and only if both contain the exact same multiset of elements. Simply sort both and compare, or use frequency counting. TutorialsPoint - Make Two Arrays Equal by Reversing Subarrays | Optimal Solution O(n log n)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
32.0K Views
Medium Frequency
~8 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen