EasyNo. 2717

Semi-Ordered Permutation — LeetCode 2717 Python Solution

Topics
Array, Simulation
Reading time
2 min

The problem

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.

Example

Input
nums = [2,1,4,3]
Output
2
Explanation
We can make the permutation semi-ordered using these sequence of operations:

Python solution

PythonSolution
class Solution:
    def semiOrderedPermutation(self, nums: List[int]) -> int:
        n = len(nums)
        i = nums.index(1)
        j = nums.index(n)
        k = 1 if i < j else 2
        return i + n - j - k

Complexity

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Related problems

Frequently asked questions

How hard is LeetCode 2717. Semi-Ordered Permutation?

LeetCode 2717. Semi-Ordered Permutation is rated Easy on LeetCode.

What is the time complexity of LeetCode 2717. Semi-Ordered Permutation?

The Python solution on this page runs in O(n), where n is the length of the array.

What is the space complexity of LeetCode 2717. Semi-Ordered Permutation?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2717. Semi-Ordered Permutation cover?

LeetCode 2717. Semi-Ordered Permutation is tagged Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.