Problem Description
Given a 0-indexed permutation of n integers, the goal is to rearrange the array so that the first element is 1 and the last element is n. The only allowed operation is swapping two adjacent elements. Return the minimum number of operations required to transform the array into a semi-ordered permutation.
Key Insights
- Identify the current positions (indices) of 1 and n in the array.
- To bring 1 to the beginning, it requires a number of swaps equal to its current index.
- To bring n to the end, it requires a number of swaps equal to (n-1 - current index of n).
- If the index of 1 is greater than the index of n, the swaps overlap resulting in one less swap overall.
- The overall time complexity is O(n) since only a single pass is needed to find the indices, and constant additional work is performed.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(1)
Solution
The solution involves scanning through the given permutation to locate the positions of 1 and n. The number of swaps required to bring 1 to the beginning is equal to its current index (since each adjacent swap moves it one position to the left). Similarly, the number of swaps to bring n to the end is (n-1 - index of n). However, if the index of 1 comes after the index of n, one swap will effectively move both elements at the same time, so we subtract one from the total count. This approach uses simple arithmetic calculations and a single traversal to determine indices.