Sort Array By Parity II — LeetCode 922 Python Solution

EasyArrayTwo PointersSorting
Problem
#922
Reading time
2 min

The problem

Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Example

Input
nums = [4,2,5,7]
Output
[4,5,2,7]
Explanation
[4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.

Python solution

Python
class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        n, j = len(nums), 1
        for i in range(0, n, 2):
            if nums[i] % 2:
                while nums[j] % 2:
                    j += 2
                nums[i], nums[j] = nums[j], nums[i]
        return nums

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{nums}
SpaceO(1) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 922. Sort Array By Parity II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 922. Sort Array By Parity II?
LeetCode 922. Sort Array By Parity II is rated Easy on LeetCode.
What is the time complexity of LeetCode 922. Sort Array By Parity II?
The Python solution on this page runs in O(n), where n is the length of the array \textit{nums}.
What is the space complexity of LeetCode 922. Sort Array By Parity II?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 922. Sort Array By Parity II cover?
LeetCode 922. Sort Array By Parity II is tagged Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview