Beats 100% || Easy to Understand || Two pointer approach || With Explanation 🔥
\nPlease Upvote if you find the solution helpful\n\n\n\n\n---\n\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe algorithm us
\nPlease **Upvote** if you find the solution helpful\n\n![LeetCode.png](https://assets.leetcode.com/users/images/43938448-e206-4689-bf16-57db27cd7dd3_1709645620.0873218.png)\n\n\n---\n\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe algorithm uses two pointers to maintain the positions of even and odd numbers. As it traverses the array, even numbers are placed at the beginning, and odd numbers are placed at the end.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize three variables: ans as the result array, and two pointers idx (for even numbers) and j (for odd numbers).\n2. Iterate through the input array nums.\n    - If the current number is even (nums[i] % 2 == 0), place it at the idx position in the ans array and increment idx.\n    - If the current number is odd, place it at the j position in the ans array and decrement j.\n3. Return the sorted array ans.\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n    public int[] sortArrayByParity(int[] nums) {\n        int n=nums.length;\n        int ans[]=new int[n];\n        int idx=0;\n        int j=n-1;\n        for(int i=0;i<n;i++){\n            if(nums[i]%2==0){\n                ans[idx]=nums[i];\n                idx++;\n            }\n            else{\n                ans[j]=nums[i];\n                j--;\n            }\n        }\n        return ans;\n    }\n}\n```\n\n---\n\n
['Array', 'Two Pointers', 'Java']