#2717
Semi-Ordered Permutation
EasyArraySimulationArraySimulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the positions of 1 and n to calculate the minimum swaps needed directly, avoiding unnecessary iterations. This is efficient and straightforward.
⚙️
Algorithm
3 steps- 1Step 1: Find the index of 1 (let's call it x) and the index of n (let's call it y).
- 2Step 2: If x < y, the answer is x + (n - y - 1).
- 3Step 3: If x > y, the answer is x + (n - y - 1) - 1.
solution.py11 lines
1# Full working Python code
2
3def min_swaps(nums):
4 n = len(nums)
5 x = nums.index(1)
6 y = nums.index(n)
7 if x < y:
8 return x + (n - y - 1)
9 else:
10 return x + (n - y - 1) - 1
11ℹ
Complexity note: This solution is linear because we only traverse the array a couple of times to find the indices of 1 and n, making it very efficient.
- 1The positions of 1 and n are crucial in determining the number of swaps needed.
- 2The order of elements between 1 and n does not affect the swap count as long as they are in the correct positions.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.