C++||Solutions🚀||Explained Line by Line ✔✔||Easy to understand😊||Beginner Friendly🚀✔✔
Intuition\n Describe your first thoughts on how to solve this problem. \nThe code works based on the intuition that for a semi-ordered permutation, we need to b
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code works based on the intuition that for a semi-ordered permutation, we need to bring the number 1 to the front of the array and the maximum number to the end. The number of elements between these two positions represents the elements that need to be rearranged. By finding the positions of 1 and the maximum number, the code calculates the answer accordingly.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code uses two pointers, l and r, to keep track of the positions of specific numbers in the array.\n\nIt iterates over the elements of the array to find the last occurrences of the numbers 1 and the maximum number.\n\nIt calculates the answer by adding the position of the last occurrence of 1 (l) and the number of elements between the right pointer (r) and the end of the array.\n\nIf there are duplicate elements between the two pointers (l > r), it adjusts the answer by decrementing it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the code is O(n), where n is the size of the input array nums. This is because the code iterates over the array once to find the positions of 1 and the maximum number. The time taken is directly proportional to the size of the input array. Therefore, the time complexity is linear with respect to the input size.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the code is O(1), as it uses a constant amount of extra space to store the left pointer (l), the right pointer (r), and the answer. The space usage does not depend on the size of the input array.\n\n# Code\n```\nclass Solution {\npublic:\n int semiOrderedPermutation(vector<int>& nums) {\n    int l = 0, r = 0;\n    for(int i = 0; i < nums.size(); i++) {\n        if(nums[i] == 1)\n            l = i; // Update the left pointer if the current number is 1\n        if(nums[i] == nums.size())\n            r = i; // Update the right pointer if the current number is equal to the size of the array\n    }\n    int ans = l + (nums.size() - 1 - r); // Calculate the answer by adding the left pointer position and the number of elements between the right pointer and the end of the array\n    if(l > r)\n        ans--; // Adjust the answer if the left pointer is greater than the right pointer\n    return ans; // Return the calculated answer\n}\n};\n```
['C++']