The Fastest 100% Runtime JS/TS Solution
Approach\n Describe your approach to solving the problem. \nWe find indexes of the smallest firstIndex and the largest lastIndex integers in the array.\nIf they
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe find indexes of the smallest `firstIndex` and the largest `lastIndex` integers in the array.\nIf they are placed at the start and at the end of the array respectively, we immediately return `0`.\nThen we check whether the index of the smallest digit is less than the index of the biggest digit. \nIf it is, we return the sum of two differences:\n- a distance between 0 and `firstIndex`,\n- a distance between `nums.length - 1` and `lastIndex`.\n\nOtherwise, we return the same with substraction of 1 as an unnesesary step for swapping.\n\n![Screenshot 2024-10-19 143704.png](https://assets.leetcode.com/users/images/e3629c8c-6955-42b5-b443-6f63e9c3b2cd_1729337956.215484.png)\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```javascript []\nconst semiOrderedPermutation = (nums) => {\n  const len = nums.length;\n  const firstIndex = nums.indexOf(1);\n  const lastIndex = nums.indexOf(len);\n\n  if (firstIndex === 0 && lastIndex === len - 1) return 0;\n\n  return firstIndex < lastIndex\n    ? firstIndex + (len - 1 - lastIndex)\n    : firstIndex + (len - 1 - lastIndex) - 1;\n};\n```\n\n# Code\n```typescript []\nconst semiOrderedPermutation = (nums: number[]): number => {\n  const len: number = nums.length;\n  const firstIndex: number = nums.indexOf(1);\n  const lastIndex: number = nums.indexOf(len);\n\n  if (firstIndex === 0 && lastIndex === len - 1) return 0;\n\n  return firstIndex < lastIndex\n    ? firstIndex + (len - 1 - lastIndex)\n    : firstIndex + (len - 1 - lastIndex) - 1;\n};\n```
['TypeScript', 'JavaScript']