O(N) Approach || C++ ✅
\n# Code\n\nclass Solution {\npublic:\n    int semiOrderedPermutation(vector<int>& nums) {\n        int n = nums.size();\n        if(nums[0] == 1 && nums[n-1] =
\n# Code\n```\nclass Solution {\npublic:\n    int semiOrderedPermutation(vector<int>& nums) {\n        int n = nums.size();\n        if(nums[0] == 1 && nums[n-1] == n)\n            return 0;\n        int lo = 0, hi = n-1;\n        for(int i = 0;i  < n; i++){\n            if(nums[i] == 1){\n                lo = i;\n            }\n            if(nums[i] == n){\n                hi = i;\n            }\n        }\n        int ans;\n        if(lo > hi){\n            ans = lo + abs(n-1-hi-1);\n        }\n        else{\n            ans = lo + abs(n-1-hi);\n        }\n        return ans;\n    }\n};\n```
['C++']