#2717
Easy Algorithms Semi ordered permutation
Array Simulation
64.1% acceptance
Feb 25, 2026
228
21
You are given a 0-indexed permutation of n integers nums.
A permutation is called semi-ordered if the first number equals 1 and the last number equals n. You can perform the below operation as many times as you want until you make nums a semi-ordered permutation:
Pick two adjacent elements in nums, then swap them.
Return the minimum number of operations to make nums a semi-ordered permutation.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn semi_ordered_permutation(nums: Vec<i32>) -> i32 {
let n = nums.len();
let idx1 = nums.iter().position(|&x| x == 1).unwrap();
let idxn = nums.iter().position(|&x| x == n as i32).unwrap();
let mut ops = idx1 + (n - 1 - idxn);
if idx1 > idxn { ops -= 1; }
ops as i32
}
}