🤩easy understanding✅with intuition and approach and explanation✅
Intuition\n Describe your first thoughts on how to solve this problem. \nI got to reach the solution with the help of some examples\nYou may understand with the
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI got to reach the solution with the help of some examples\nYou may understand with the help of:-\nexample 1: arr1=[2,1,4,3]\n- first thing to observe is that the position of 1 and n are such that 1 appears before n\n- we see that we have to swap the elements [((n-1)-position of n)+(position of first-0)]number of times\n\nexample 2: arr2=[2,4,1,3]\n- first thing to observe is that the position of 1 and n are such that 1 appears after n\n- we see that we have to swap the elements [((n-1)-position of n)+(position of first-0)]number of times\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. store the index of 1 and n\n2. let us say index of 1 = first and n=last\n3. the value of ans will be=((n-1)-last)+(first-0)\n4. check if first > last\n5. if so then decrease the value of answer(because we can see that we will be swapping once less as there will be a condition when 1 and n will be swapped,so need to count this just once)\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    int semiOrderedPermutation(vector<int>& arr) {\n        int n=arr.size();\n        int first=-1,last=-1;\n        //first store the index of 1 and n\n        for(int i=0;i<n;i++){\n            if(arr[i]==n)last=i;\n            if(arr[i]==1)first=i;\n        }\n        //now when we observe the solution with a few examples we get to know that there are two cases\n        int ans=-1;\n        if(last<first){\n            ans=((n-1)-last)+(first-0);\n            ans--;\n        }\n        else{\n            ans=((n-1)-last)+(first-0);\n        }\n        return ans;\n    }\n};\n```
['Math', 'Brainteaser', 'C++']