Editorial
Core insight
Sort Array By Parity · Two Pointers
Core Insight for Sort Array By Parity
The core insight for the optimal LeetCode 905 Solution is to view the array as a container that needs to be partitioned. We can maintain an invariant where the left side of the array only contains even numbers and the right side only contains odd numbers.
We define two pointers:
left: Starts at the beginning (0) and looks for odd numbers that are out of place.right: Starts at the end (n-1) and looks for even numbers that are out of place.
The logic proceeds by checking the elements at these pointers:
- If
nums[left]is even, it is already in the correct position relative to the partition. We advanceleft. - If
nums[right]is odd, it is already in the correct position. We decrementright. - If
nums[left]is odd ANDnums[right]is even, both elements are in the wrong partition. We swap them. After the swap, the element atleftbecomes even (correct) and the element atrightbecomes odd (correct).
Visual Description:
Imagine the array indices as a horizontal range. The left pointer defines the boundary of the "processed even" region growing from the start. The right pointer defines the boundary of the "processed odd" region growing from the end. The area between left and right is the "unprocessed" zone. The algorithm shrinks this unprocessed zone until it vanishes when left meets right.

Deep dive
Full breakdown
Full reasoning, pitfalls, and implementation flow
LeetCode 905: Sort Array By Parity Solution & Explanation
Problem Overview
TL;DR: Use two pointers starting at opposite ends of the array to swap elements in place, ensuring even numbers settle on the left and odd numbers on the right.
The Sort Array By Parity problem requires us to reorder an array of integers so that all even integers appear before all odd integers. The relative order of the even numbers or the odd numbers among themselves does not matter; any valid permutation that satisfies the "evens first, odds last" condition is acceptable. This is a fundamental array manipulation problem often used to test understanding of in-place algorithms.
This is a popular interview question that serves as an excellent introduction to partitioning algorithms, similar to those found in QuickSort.
Brute Force Approach for Sort Array By Parity
The most intuitive way to solve LeetCode 905 is to create a new array and populate it in two passes.
- Create a new result array
res. - Iterate through the input
numsarray. If a number is even, append it tores. - Iterate through the input
numsarray again. If a number is odd, append it tores. - Return
res.
Pseudo-code
function sortArrayByParity(nums):
result = []
for x in nums:
if x is even:
result.append(x)
for x in nums:
if x is odd:
result.append(x)
return resultComplexity Analysis
- Time Complexity: , where is the number of elements. We iterate through the array twice.
- Space Complexity: . We allocate a new array of size to store the result.
Why it fails (Context)
While this solution is correct and passes LeetCode's time constraints, it fails to meet the standard expectation for this class of problems in technical interviews. The problem tags and typical constraints imply an in-place solution is preferred. Allocating extra space is inefficient when the operation can be performed by modifying the input array directly with space.
Algorithm Strategy: Two Pointer Patterns
- Initialization: Set a
leftpointer to index0and arightpointer to indexn - 1. - Loop Condition: Continue execution as long as
left < right. - Left Scan: Check the value at
nums[left]. Ifnums[left] % 2 == 0(even), this element is correctly placed. Incrementleftto process the next element. - Right Scan: Check the value at
nums[right]. Ifnums[right] % 2 != 0(odd), this element is correctly placed. Decrementrightto process the previous element. - Swap: If the execution reaches this point inside the loop, it implies
nums[left]is odd andnums[right]is even. Swapnums[left]andnums[right]. - Termination: Once the pointers cross, all even numbers are to the left of the convergence point, and all odd numbers are to the right. Return the modified
numsarray.
Execution Flow
Consider the input nums = [3, 1, 2, 4].
-
Start:
left = 0,right = 3.nums[left]is 3 (Odd). It is out of place.nums[right]is 4 (Even). It is out of place.- Action: Swap
nums[0]andnums[3]. - Array becomes
[4, 1, 2, 3]. Incrementleft, decrementright.
-
Iteration 2:
left = 1,right = 2.nums[left]is 1 (Odd). It is out of place.nums[right]is 2 (Even). It is out of place.- Action: Swap
nums[1]andnums[2]. - Array becomes
[4, 2, 1, 3]. Incrementleft, decrementright.
-
Iteration 3:
left = 2,right = 1.- Condition
left < rightis false. - Stop.
- Condition
-
Result:
[4, 2, 1, 3]. (Note: This is one valid output; evens4, 2are first, odds1, 3are last).
Proof of Correctness
The algorithm maintains the invariant that all elements in the range [0, left) are even and all elements in the range (right, n-1] are odd.
- In each step, we either increment
left(validating an even number), decrementright(validating an odd number), or swap an invalid pair to make them valid. - Since the distance between
leftandrightdecreases strictly with every valid operation or swap, the loop must terminate. - Upon termination (
left >= right), the union of the validated regions covers the entire array, ensuring the partition property holds.
Pattern Reuse Notes
The Two Pointers - In-place Array Modification pattern used in Sort Array By Parity is highly reusable. Mastering this logic allows you to solve several other high-frequency interview problems:
- LeetCode 26: Remove Duplicates from Sorted Array - Uses a generic "read" and "write" pointer strategy to filter elements.
- LeetCode 27: Remove Element - Partitioning the array into "kept" and "removed" elements.
- LeetCode 75: Sort Colors - A more complex variation involving three partitions (0, 1, 2) instead of two (even, odd).
- LeetCode 80: Remove Duplicates from Sorted Array II - Similar to LC 26 but with relaxed constraints on duplicates.
In all these cases, the key is managing boundaries within the array to segregate data without external storage.
Feynman coach · Before you peek at the code
Can you explain the core insight in your own words?
If you can explain it before reading code, you’re far more likely to recall it under interview pressure.
Reference Implementation
C++ Solution for LeetCode 905
1class Solution {
2public:
3 vector<int> sortArrayByParity(vector<int>& nums) {
4 int left = 0;
5 int right = nums.size() - 1;
6
7 while (left < right) {
8 if (nums[left] % 2 == 0) {
9 // Left element is already even (correct), move forward
10 left++;
11 } else if (nums[right] % 2 != 0) {
12 // Right element is already odd (correct), move backward
13 right--;
14 } else {
15 // Left is odd and Right is even: Swap them
16 std::swap(nums[left], nums[right]);
17 left++;
18 right--;
19 }
20 }
21
22 return nums;
23 }
24};Java Solution for LeetCode 905
1class Solution {
2 public int[] sortArrayByParity(int[] nums) {
3 int left = 0;
4 int right = nums.length - 1;
5
6 while (left < right) {
7 if (nums[left] % 2 == 0) {
8 // Left is even, correct position
9 left++;
10 } else if (nums[right] % 2 != 0) {
11 // Right is odd, correct position
12 right--;
13 } else {
14 // Left is odd, Right is even -> Swap
15 int temp = nums[left];
16 nums[left] = nums[right];
17 nums[right] = temp;
18
19 left++;
20 right--;
21 }
22 }
23
24 return nums;
25 }
26}Python Solution for LeetCode 905
1class Solution:
2 def sortArrayByParity(self, nums: List[int]) -> List[int]:
3 left = 0
4 right = len(nums) - 1
5
6 while left < right:
7 if nums[left] % 2 == 0:
8 # Left is even, correct position
9 left += 1
10 elif nums[right] % 2 != 0:
11 # Right is odd, correct position
12 right -= 1
13 else:
14 # Left is odd, Right is even -> Swap
15 nums[left], nums[right] = nums[right], nums[left]
16 left += 1
17 right -= 1
18
19 return nums