Make Two Arrays Equal by Reversing Subarrays: Frequency Count Pattern
LeetCode 1460. Make Two Arrays Equal by Reversing Subarrays gives you two integer arrays target and arr of the same length. You are allowed to reverse any subarray of arr any number of times. The question: can you make arr equal to target?
At first glance, this feels like it could require some clever sequence of reversal operations. But the real answer is much simpler than that.
Why this problem matters
This problem is a great example of how the hardest part of a problem is sometimes recognizing what does not matter. The problem description goes out of its way to describe subarray reversals, complete with indices and mechanics. It is tempting to start thinking about which subarrays to reverse and in what order.
But here is the thing: subarray reversals are a red herring. If two arrays contain the same elements with the same frequencies, you can always rearrange one into the other using reversals. In fact, you can sort any array using nothing but subarray reversals. This means the reversal operation is powerful enough to produce any permutation.
Once you see that, the problem collapses from "figure out a sequence of reversals" to "check if two arrays have the same multiset of elements." That is a dramatically simpler question, and it has a well-known O(n) solution using frequency counting.
The key insight
You can sort any array using only subarray reversals. This is essentially what pancake sorting does: find the largest unsorted element, reverse a subarray to move it to the front, then reverse again to move it to its correct position. Repeat until sorted.
Since you can sort any array with reversals, you can definitely transform arr into target as long as both arrays contain the exact same elements with the exact same counts. If arr has a 3 that target does not, no amount of reversing will fix that. If both have the same multiset, sort arr to match the sorted version of target, then you are done.
So the entire problem reduces to: do target and arr have identical frequency distributions?
The solution
from collections import Counter
def canBeEqual(target: list[int], arr: list[int]) -> bool:
return Counter(target) == Counter(arr)
That is the entire solution. Python's Counter builds a frequency map from each array, and the == operator checks if every key has the same count in both maps.
Building a Counter takes O(n) time. Comparing two Counter objects takes O(n) time. Total: O(n) time, O(n) space.
You could also solve this without importing Counter by using a plain dictionary, but Counter is built for exactly this use case. In an interview, either approach is fine, and using Counter shows you know your standard library.
When a problem gives you a seemingly complex operation (like "reverse any subarray any number of times"), ask yourself what the operation can actually achieve. If it can produce any permutation, then the problem is really just asking whether two collections have the same elements.
Visual walkthrough
Let's trace through the frequency counting approach with target = [1, 2, 3, 4] and arr = [2, 4, 1, 3].
Step 1: Count frequencies in target = [1, 2, 3, 4]
Walk through target and count how many times each value appears.
Step 2: Count frequencies in arr = [2, 4, 1, 3]
Do the same for arr. Despite different ordering, the counts are identical.
Step 3: Compare the two frequency maps
Every element has the same frequency in both arrays, so arr can be rearranged into target.
Both frequency maps are identical: each value appears exactly once. Since the multisets match, we return True. No actual reversals needed.
Complexity analysis
| Approach | Time | Space |
|---|---|---|
| Frequency Count | O(n) | O(n) |
| Sorting | O(n log n) | O(n) |
The frequency count approach uses a hash map to count occurrences in each array, then compares the maps. This runs in O(n) time and O(n) space, where n is the length of the arrays.
The sorting approach sorts both arrays and checks if the sorted results are equal. Sorting costs O(n log n), and depending on the language, may require O(n) auxiliary space. This is a perfectly valid solution and is very readable:
def canBeEqual(target: list[int], arr: list[int]) -> bool:
return sorted(target) == sorted(arr)
Both approaches are accepted, but the frequency count solution is asymptotically faster. For an easy problem like this, interviewers are happy with either. The sorting approach has the advantage of being a single line with no imports.
The building blocks
1. Frequency counting
The core pattern here is building a frequency map: iterating through a collection and counting how many times each element appears. This is one of the most common operations in algorithm problems.
from collections import Counter
freq = Counter(arr)
Under the hood, this is equivalent to:
freq = {}
for num in arr:
freq[num] = freq.get(num, 0) + 1
You will use this pattern in problems like Valid Anagram, Top K Frequent Elements, and many more. It is worth being able to write it from memory.
2. Multiset comparison
Once you have two frequency maps, checking equality is just comparing dictionaries. In Python, Counter(a) == Counter(b) does this automatically. If any key has a different count, or one map has a key the other does not, the comparison returns False.
Counter(target) == Counter(arr)
This operation is the same one used in Valid Anagram, where you check if two strings have identical character frequencies. Learning the pattern here means you already know how to solve that problem too.
Edge cases
- Already equal arrays:
target = [1, 2, 3],arr = [1, 2, 3]. The frequency maps match trivially. ReturnTrue. - Single element:
target = [7],arr = [7]. Only one element, always matches. ReturnTrue. - All identical elements:
target = [5, 5, 5],arr = [5, 5, 5]. Same frequencies. ReturnTrue. - Different frequencies:
target = [1, 1, 2],arr = [1, 2, 2]. The count of 1 differs (2 vs 1), so returnFalse. - Same elements, different lengths: This cannot happen per the problem constraints (both arrays have the same length), but if it could, different lengths would immediately mean
False.
From understanding to recall
This problem is easy to understand once you see the insight, but the real skill is recognizing the pattern instantly when you encounter it in a new context. Many harder problems contain a subproblem that boils down to "do these two collections have the same elements?" If you have drilled the frequency counting pattern enough times, you will spot it immediately.
The other transferable lesson is learning to see through distracting problem descriptions. "Reverse any subarray any number of times" sounds like it requires simulation or BFS over states. But once you realize the operation is powerful enough to produce any permutation, the complexity evaporates. This kind of reduction, from a seemingly complex operation to a simple property check, appears in many problems across different difficulty levels.
Related posts
- Contains Duplicate - The simplest hash set problem, asking whether any element appears more than once
- Valid Anagram - Same frequency comparison technique applied to characters in two strings
- Group Anagrams - Uses sorted keys and hash maps to group strings by their character frequencies
Recognizing that "reverse any subarray" is just a fancy way of saying "rearrange freely" is the whole problem. Once that clicks, you are left with a textbook frequency counting exercise. Drill the pattern, and problems like this become instant solves.