The Minimum Adjacent Swaps to Make a Valid Array problem involves an array of integers. An array is considered "valid" if the smallest element is at the very first index (index 0) and the largest element is at the very last index. You need to calculate the minimum number of adjacent swaps to achieve this. Note that if there are multiple smallest or largest elements, you can pick any of them to move.
This is a great Minimum Adjacent Swaps to Make a Valid Array interview question for entry-level positions at Amazon. It tests a candidate's ability to calculate "Manhattan distance" in one dimension and their attention to detail regarding overlapping paths. It's a logic-heavy problem that doesn't require complex data structures but does require clear thinking about indices.
The Greedy interview pattern is the way to go here.
min_index.(N - 1) - max_index.min_index is greater than the max_index, the two elements will "cross" each other during the swaps. This saves you exactly one swap.Consider array [3, 4, 5, 2].
2 at index 3. Max is 5 at index 2.2 to index 0: 3 swaps.5 to index 3: 3 - 2 = 1 swap.min_index (3) > max_index (2), they will cross.3 + 1 - 1 = 3.
Sequence: [3, 4, 5, 2] -> [3, 4, 2, 5] -> [3, 2, 4, 5] -> [2, 3, 4, 5]. (Total 3 swaps).Always look for "interaction" between your moves. In many Greedy coding problems, doing action A might make action B easier (or harder). Identifying the "crossing" saving in this problem shows that you are thinking about the process holistically.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Largest Element in an Array after Merge Operations | Medium | Solve | |
| Minimum Health to Beat Game | Medium | Solve | |
| Removing Minimum and Maximum From Array | Medium | Solve | |
| Minimum Domino Rotations For Equal Row | Medium | Solve | |
| Maximum Distance in Arrays | Medium | Solve |