You are given a 0-indexed permutation of integers nums
(1-indexed) of length n
. A permutation means nums
contains each integer from 1
to n
exactly once.
A permutation is called semi-ordered if the first number equals 1 and the last number equals n
. More formally, for a permutation nums
it is semi-ordered if nums[0] == 1
and nums[n - 1] == n
.
You are allowed to perform any number of operations, where in each operation you can choose any two adjacent elements of nums
and swap them.
Return the minimum number of operations to make nums
semi-ordered.
n
of the permutation will be at least 1 as per the problem statement.n
of the permutation?
n
contains each integer from 1
to n
exactly once.1
and n
.1
and n
in the array.1
to the start of the array (index at 0
).n
to the end of the array (index at n-1
).1
is before or after n
, we may need to subtract one swap because moving 1
left might free up the slot that n
moves into.public class SemiOrderedPermutation {
public int minOperations(int[] nums) {
int n = nums.length;
int index1 = -1, indexN = -1;
// Find indices of 1 and n
for (int i = 0; i < n; i++) {
if (nums[i] == 1) {
index1 = i;
} else if (nums[i] == n) {
indexN = i;
}
}
// Calculate number of swaps needed to move 1 to the start
int swapsFor1 = index1;
// Calculate number of swaps needed to move n to the end
int swapsForN = (n - 1) - indexN;
// If 1 is before n, n moving will occupy the freed slot by moving 1
if (index1 < indexN) {
return swapsFor1 + swapsForN;
} else {
return swapsFor1 + swapsForN - 1;
}
}
public static void main(String[] args) {
SemiOrderedPermutation sol = new SemiOrderedPermutation();
int[] nums = {2, 4, 1, 3};
System.out.println(sol.minOperations(nums)); // Output: 3
}
}
1
and n
takes O(n).1
and n
and computes the minimum swaps needed based on their positions.1
and n
are already in proper positions is implicitly handled since the operations would result in zero swaps.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?