Problem Description
Given an integer array, you can swap only adjacent elements. The array is considered valid if the smallest element (any one if there are multiple) is at index 0 and the largest element (any one if there are multiples) is at the last index. The goal is to determine the minimum number of adjacent swaps required to rearrange the array into a valid state.
Key Insights
- Identify the leftmost occurrence of the smallest element and the rightmost occurrence of the largest element.
- The smallest element requires a number of swaps equal to its index (to move it to index 0).
- The largest element requires (n - 1 - its index) swaps (to move it to the last position).
- If the smallest element is originally placed to the right of the largest element, one swap will affect both, so reduce the total count by one.
Space and Time Complexity
Time Complexity: O(n) – scanning the array a couple of times. Space Complexity: O(1) – using constant extra space.
Solution
First, scan the array to determine:
- The leftmost index where the minimum value appears.
- The rightmost index where the maximum value appears. Then, calculate the minimum swaps as: swaps = (minIndex) + ((n - 1) - maxIndex) If minIndex > maxIndex (i.e., the smallest element is to the right of the maximum element), subtract one from the total swaps due to the overlapping swap effect. This approach directly maps to the operations allowed (adjacent swaps) and guarantees the minimal number of moves.