Sort Array By Parity — LeetCode 905 Python Solution

EasyArrayTwo PointersSorting
Problem
#905
Reading time
2 min

The problem

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. Return any array that satisfies this condition.

Example

Input
nums = [3,1,2,4]
Output
[2,4,3,1]
Explanation
The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.

Python solution

Python
class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        i, j = 0, len(nums) - 1
        while i < j:
            if nums[i] % 2 == 0:
                i += 1
            elif nums[j] % 2 == 1:
                j -= 1
            else:
                nums[i], nums[j] = nums[j], nums[i]
                i, j = i + 1, j - 1
        return nums

Complexity

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

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 905. Sort Array By Parity 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 905. Sort Array By Parity?
LeetCode 905. Sort Array By Parity is rated Easy on LeetCode.
What is the time complexity of LeetCode 905. Sort Array By Parity?
The Python solution on this page runs in O(n), where n is the length of the array nums.
What is the space complexity of LeetCode 905. Sort Array By Parity?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 905. Sort Array By Parity cover?
LeetCode 905. Sort Array By Parity 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