✅✅C++ two pointer Best Solution. Detailed Explanation with comments
Intuition\n Describe your first thoughts on how to solve this problem. \nIt is given that the number of odd and even elements is the same. Now, if even elements
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is given that the number of odd and even elements is the same. Now, if even elements are in even positions, then automatically odd elements will be in odd positions.\n This provides the insight that if k even elements are in odd positions, then there must be k odd elements in even positions.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitially, I set i=0 and j=1.\nNOTE:- "i" will keep track of even places, and "j" will keep track of odd places.\n\nSo, if even elements are in even positions and odd elements are in odd positions, then no action is required.\n\nHowever, if this is not the case, then Swapping will occur when either of the two conditions is met:-\n\n 1. The element nums[i] is in an odd position, and it is waiting for nums[j] to be found at an even position.\n   \n2. The element nums[j] is in an even position, and it is waiting for nums[i] to be found at an odd position.\n\n            \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n    vector<int> sortArrayByParityII(vector<int>& nums) {\n        int n = nums.size();\n        int i=0; //i will keep track of even place\n        int j = 1; //j will keep track of odd place\n        while(i<n && j<n){\n            if(nums[i]%2==0) i+=2; //No need to change(i.e already in even place)\n            else if(nums[j]%2==1) j+=2;//No need to change(i.e already in odd place)\n            else swap(nums[i],nums[j]); \n            /* Swapping will occur when either of the two conditions is met:-\n           1. The element nums[i] will be in an odd position, and it will wait until \n            nums[j] is found at an even position.\n\n           2. The element nums[j] will be in an even position, and it will wait until \n            nums[i] is found at an odd position.\n            */\n        }\n        return nums;\n    }\n};\n```\n![Screenshot 2024-02-19 172132.png](https://assets.leetcode.com/users/images/a3f758c0-1c71-4b67-854c-4bb2fbb3a0ca_1708343567.1240585.png)
['C++']