Leetcode 958 Solution

This article provides solution to leetcode question 958 (sort-array-by-parity-ii)

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

Solution

class Solution:
    def sortArrayByParityII(self, A: List[int]) -> List[int]:
        def next_i(A, i, parity):
            while i < len(A):
                if A[i] % 2 == parity:
                    return i
                i += 1
            return len(A)

        i1 = next_i(A, 0, 1)
        i2 = next_i(A, 0, 0)

        ans = []

        while i1 < len(A) or i2 < len(A):
            if len(ans) % 2:
                ans.append(A[i1])
                i1 = next_i(A, i1 + 1, 1)
            else:
                ans.append(A[i2])
                i2 = next_i(A, i2 + 1, 0)

        return ans