Loading problems...
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.
The most intuitive way to solve LeetCode 905 is to create a new array and populate it in two passes.
res.nums array. If a number is even, append it to res.nums array again. If a number is odd, append it to res.res.textfunction 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 result
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.
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:
nums[left] is even, it is already in the correct position relative to the partition. We advance left.nums[right] is odd, it is already in the correct position. We decrement right.nums[left] is odd AND nums[right] is even, both elements are in the wrong partition. We swap them. After the swap, the element at left becomes even (correct) and the element at right becomes 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.

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.nums[0] and nums[3].[4, 1, 2, 3]. Increment left, decrement right.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.nums[1] and nums[2].[4, 2, 1, 3]. Increment left, decrement right.Iteration 3: left = 2, right = 1.
left < right is false.Result: [4, 2, 1, 3]. (Note: This is one valid output; evens 4, 2 are first, odds 1, 3 are last).
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.
left (validating an even number), decrement right (validating an odd number), or swap an invalid pair to make them valid.left and right decreases strictly with every valid operation or swap, the loop must terminate.left >= right), the union of the validated regions covers the entire array, ensuring the partition property holds.cppclass Solution { public: vector<int> sortArrayByParity(vector<int>& nums) { int left = 0; int right = nums.size() - 1; while (left < right) { if (nums[left] % 2 == 0) { // Left element is already even (correct), move forward left++; } else if (nums[right] % 2 != 0) { // Right element is already odd (correct), move backward right--; } else { // Left is odd and Right is even: Swap them std::swap(nums[left], nums[right]); left++; right--; } } return nums; } };
javaclass Solution { public int[] sortArrayByParity(int[] nums) { int left = 0; int right = nums.length - 1; while (left < right) { if (nums[left] % 2 == 0) { // Left is even, correct position left++; } else if (nums[right] % 2 != 0) { // Right is odd, correct position right--; } else { // Left is odd, Right is even -> Swap int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; left++; right--; } } return nums; } }
pythonclass Solution: def sortArrayByParity(self, nums: List[int]) -> List[int]: left = 0 right = len(nums) - 1 while left < right: if nums[left] % 2 == 0: # Left is even, correct position left += 1 elif nums[right] % 2 != 0: # Right is odd, correct position right -= 1 else: # Left is odd, Right is even -> Swap nums[left], nums[right] = nums[right], nums[left] left += 1 right -= 1 return nums
Time Complexity:
Each element in the array is accessed a constant number of times (at most once by left and once by right). The total operations are linear with respect to the array size .
Space Complexity:
The sorting happens in-place. We only use two integer variables (left and right) for tracking indices, regardless of the input size.
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:
In all these cases, the key is managing boundaries within the array to segregate data without external storage.
Why does the naive solution fail interviews?
Why do I get an infinite loop?
left and decrement right afterward.Why is my logic failing on edge cases?
nums[right] when right has become negative.left <= right without internal checks) can cause out-of-bounds errors.left < right naturally handles single-element arrays by skipping the loop entirely.