Problem statement

https://leetcode.com/problems/sort-array-by-parity-ii/

Solution

If we want to have O(1) space complexity solution, we need to use two pointers approach.

Complexity

It is O(n) for time and O(1) for space.

Code

class Solution:
    def sortArrayByParityII(self, nums):
        i, j, n = 0, 1, len(nums)
        while j < n and i < n:
            if nums[i] % 2 == 0:
                i += 2
            elif nums[j] % 2 == 1:
                j += 2
            else:
                nums[i], nums[j] = nums[j], nums[i]
        return nums