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 Subarraystarget:1234arr:2413can reversesubarrays?Key Insight:Reversing subarrays onlychanges ORDER of elements,not the elements themselves!Arrays can be equal iff theycontain the same elementsBoth arrays contain: {1, 2, 3, 4}✓ Result: trueSolution: Sort both arrays and compare them
Understanding the Visualization
1
Input
Two arrays: target=[1,2,3,4] and arr=[2,4,1,3]
2
Process
Check if arrays contain same elements (reversals only change order, not values)
3
Output
Return true if same elements, false otherwise
Key Takeaway
🎯 Key Insight: Subarray reversals can rearrange elements into any order, so arrays are equal if they contain the same elements
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