Leetcode 2717: Semi-Ordered Permutation

grid47
grid47
Exploring patterns and algorithms
Feb 9, 2024 5 min read

You are given a permutation of integers from 1 to n. A permutation is called semi-ordered if the first element equals 1 and the last element equals n. You can perform the operation of swapping two adjacent elements as many times as needed to make the permutation semi-ordered. Your task is to return the minimum number of swaps required.
Problem
Approach
Steps
Complexity
Input: A list of integers `nums` representing a permutation of numbers from 1 to `n`.
Example: nums = [3, 1, 4, 2]
Constraints:
• 2 <= nums.length <= 50
• nums contains a permutation of integers from 1 to n.
Output: Return the minimum number of adjacent swaps required to make the permutation semi-ordered.
Example: 3
Constraints:
• The output is a non-negative integer.
Goal: The goal is to count the minimum number of adjacent swaps needed to make the permutation semi-ordered.
Steps:
• Identify the positions of the numbers 1 and n.
• Calculate the number of swaps required to move the 1 to the start and n to the end.
• Adjust for the case where 1 and n are out of order in relation to each other.
Goal: The input list will always be a valid permutation of integers from 1 to n.
Steps:
• 2 <= nums.length <= 50
• nums contains a permutation of integers from 1 to n.
Assumptions:
• The input will always be a valid permutation with no duplicates.
Input: Example 1
Explanation: In the case of `nums = [3, 1, 4, 2]`, the required number of swaps is 3. First, we swap `3` and `1`, then swap `4` and `2`, and finally swap `3` and `2`.

Input: Example 2
Explanation: In the case of `nums = [2, 4, 1, 3]`, the required number of swaps is 4. First, we swap `2` and `1`, then swap `4` and `3`, and finally swap `2` and `3`.

Input: Example 3
Explanation: In the case of `nums = [1, 3, 4, 2, 5]`, the required number of swaps is 2. First, we swap `4` and `2`, then swap `3` and `2`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus