Skip to content

Parity Sorting

LeetCode

01 · Question

Given an array of integers arr, modify it in place to put all even numbers before all odd numbers. The relative order between even numbers does not matter. Same for the odd numbers.

Example 1:

  • Input: arr = [3, 1, 2, 4, 6]
  • Output: [2, 4, 6, 1, 3]
  • Explanation: [4, 2, 6, 3, 1] is also accepted.

Example 2:

  • Input: arr = [1, 1, 1, 1]
  • Output: [1, 1, 1, 1]

02 · Solution

Reference solution

1def sortArrayByParity(nums: List[int]) -> List[int]:
2 l, r = 0, len(nums) - 1
3
4 while l < r:
5 if nums[l] % 2 == 0:
6 l += 1
7 elif nums[r] % 2 == 1:
8 r -= 1
9 else:
10 nums[l], nums[r] = nums[r], nums[l]
11 l += 1
12 r -= 1
13
14 return nums