15% off all plans & roadmaps Use code
See plansSort Array By Parity
- LeetCode 905
- Easy
- Two Pointers
- In-place Array Modification
Updated
TL;DR: Rearrange an integer array so every even number comes before every odd number. Any valid order is accepted, so two pointers can swap misplaced pairs in place without a second array.
Problem
You are given an integer array nums. Move every even integer to the front of the array and every odd integer after them.
Return any array that meets this condition.
Example 1
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.
Example 2
Input: nums = [0] Output: [0]
Constraints
1 <= nums.length <= 50000 <= nums[i] <= 5000
Constraints that matter
- With n up to 5000, an O(n^2) pair check is still fast enough, so the limit does not force a linear solution. Aim for O(n) anyway, because that is the bar interviewers expect.
- Values are between 0 and 5000, so the parity test is
x % 2. Zero counts as even. - Every value is nonnegative, so
x % 2returns 0 or 1 in every language. Negative inputs would change this, and a follow-up below covers that case. - The problem accepts any valid order. You do not need a stable partition, and that is what allows swaps to use O(1) extra space.
- The array has at least one element, so the code must handle n = 1 without reading outside the array.
Hints
Hint 1
This is a partition problem.
Hint 2
The naive method builds a fresh result by copying every even value first, then every odd value.
Solution
Intuition
This is a partition problem. You split the array into two groups, evens and odds, and place one group before the other. The statement says nothing about the order inside each group. That means only the split matters, not the positions of individual values within a group.
Picture two people walking toward each other along a row of cards, each stopping at a card on the wrong side. The two stopped cards trade places, then both walkers keep moving inward until they meet.
The pattern is two pointers in place. Put one pointer at the start and one at the end, and move them toward each other. The left pointer stops on an odd value and the right pointer stops on an even value. Both are on the wrong side, so swap them.
The swap works because it fixes two mistakes at once. After it, the left slot holds an even value and the right slot holds an odd value. Everything left of left is even, and everything right of right is odd. When the pointers meet, the whole array is partitioned, and no value has been copied into a second array.
Worked example
Input: nums = [5, 2, 7, 8, 1, 4, 3, 6] Output: [2, 8, 4, 6, 5, 7, 1, 3] Explanation: The evens 2, 8, 4, and 6 come first, and the odds 5, 7, 1, and 3 follow. Each group keeps its input order in this output. Any order with all evens first is also correct, so the two-pointer trace below ends on a different valid answer.
Approach 1: Brute force: two passes into a new array
The naive method builds a fresh result by copying every even value first, then every odd value. You scan the input twice and write each value once. Most candidates write this first, and it is correct. The cost is a second array of size n, which the problem does not require.
Steps
- Create an empty result list with room for n values.
- Scan
numsfrom left to right and append each even value to the result. - Scan
numsagain from left to right and append each odd value to the result. - Return the result.
Dry run
Start with [5, 2, 7, 8, 1, 4, 3, 6]. The first pass collects the evens in input order: 2, 8, 4, 6. The second pass collects the odds in input order: 5, 7, 1, 3. The result is [2, 8, 4, 6, 5, 7, 1, 3], which matches the Output line exactly, and each value is read once per pass and written once.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Let n be the array length. Each of the two passes reads all n values and does O(1) work per value, so the total is about 2n steps, which is O(n). The result list holds up to n values, so the extra space is O(n). The input array is given and is not counted.
PythonTested in our runner
from typing import List, Optional
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
evens = [x for x in A if x % 2 == 0]
odds = [x for x in A if x % 2 != 0]
return evens + oddsApproach 2: Sort by parity key
What is slow: the brute force writes every value into a second array. The insight is that only each value's parity matters, so the fix must keep the partition inside the input.
Give each value a key, 0 for even and 1 for odd, and sort by that key. A sort places all 0 keys before all 1 keys and rearranges the array itself.
The sort does more work than the task needs. It orders every pair of keys, but you only need two groups. That extra work is why this approach costs n log n time, while the next approach costs n.
Steps
- Define the key of each value as
x % 2, which is 0 for even and 1 for odd. - Sort the array by that key, using the language's sort with a key or comparator.
- Return the array.
Dry run
The keys for [5, 2, 7, 8, 1, 4, 3, 6] are [1, 0, 1, 0, 1, 0, 1, 0]. Sorting by key moves the four 0 keys (2, 8, 4, 6) to the front and the four 1 keys (5, 7, 1, 3) to the back. Python's sort and JavaScript's sort are stable, so each group keeps its input order and the result is [2, 8, 4, 6, 5, 7, 1, 3]. C++ and C# sorts are not stable, so they can return the same two groups in another order, which is still valid.
Complexity
| Time | O(n log n) |
|---|---|
| Space | O(log n) to O(n), depending on the library sort |
Let n be the array length. A comparison sort does about n log n comparisons, since about log n levels each touch n values, and each comparison computes two parities in O(1). Extra space is the sort's own bookkeeping: a recursion stack of O(log n) for quicksort-style sorts, or a temporary buffer of up to n/2 values for merge-style sorts such as Python's Timsort. The Java version boxes each value into an Integer array, which adds O(n) memory.
PythonTested in our runner
from typing import List, Optional
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
# Key 0 for even, 1 for odd. Timsort is stable and sorts A in place.
A.sort(key=lambda x: x % 2)
return AThe In-place Array Modification infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
In-place Array Modification
Part of Two Pointers
Approach 3: Two pointers from both endsOptimalIn-place Array Modification
What is slow: the sort compares pairs it never needs to order, so it spends n log n work on a two-way split. The insight is that misplaced values are easy to find from each end.
Scan from the left until you hit an odd value, and scan from the right until you hit an even value. Those two are on the wrong side, so swap them. Each index is checked a constant number of times, and no extra array is needed.
Steps
- Set
leftto 0 andrightto n - 1. - While
left < right, checkA[left]. If it is even, add 1 toleftand go back to the loop test. - Otherwise check
A[right]. If it is odd, subtract 1 fromrightand go back to the loop test. - Otherwise
A[left]is odd andA[right]is even. Swap them, then add 1 toleftand subtract 1 fromright. - When the loop ends, return
A.
Dry run
Start with [5, 2, 7, 8, 1, 4, 3, 6]. The table shows the state before each check.
| Step | left | right | A[left] | A[right] | Action | Array after |
|---|---|---|---|---|---|---|
| 1 | 0 | 7 | 5 | 6 | 5 is odd and 6 is even, so swap and move both | [6, 2, 7, 8, 1, 4, 3, 5] |
| 2 | 1 | 6 | 2 | 3 | 2 is even, so move left | [6, 2, 7, 8, 1, 4, 3, 5] |
| 3 | 2 | 6 | 7 | 3 | 7 is odd and 3 is odd, so move right | [6, 2, 7, 8, 1, 4, 3, 5] |
| 4 | 2 | 5 | 7 | 4 | 7 is odd and 4 is even, so swap and move both | [6, 2, 4, 8, 1, 7, 3, 5] |
| 5 | 3 | 4 | 8 | 1 | 8 is even, so move left | [6, 2, 4, 8, 1, 7, 3, 5] |
| 6 | 4 | 4 | 1 | 1 | left equals right, so stop | [6, 2, 4, 8, 1, 7, 3, 5] |
The trace ends on [6, 2, 4, 8, 1, 7, 3, 5]. Every even value is before every odd value, so it is valid. It is not the Output line, because swaps do not keep input order and the problem accepts any valid order.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the array length. The gap right - left starts at n - 1 and each iteration lowers it by at least 1, because a move lowers it by 1 and a swap lowers it by 2. So there are at most n - 1 iterations, each doing O(1) work.
The only extra memory is the two indices and a temporary value for the swap, so the space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
left, right = 0, len(A) - 1
while left < right:
if A[left] % 2 == 0:
# Even value already on the left side
left += 1
elif A[right] % 2 != 0:
# Odd value already on the right side
right -= 1
else:
# Odd on the left and even on the right: swap them
A[left], A[right] = A[right], A[left]
left += 1
right -= 1
return ACommon mistakes
elif A[right] % 2 == 0:on the right side. This movesrightpast the even values, which are the values that must leave the right side. Advancerightonly when the value is odd, withA[right] % 2 != 0.- Swapping whenever
A[left]is odd, without checkingA[right]. If both values are odd, the swap changes nothing, yet both pointers move and an odd value stays inside the even prefix. CheckA[right]before the swap. - Testing the same parity in both passes of the brute force. If the second loop also checks
x % 2 == 0, the odds are never collected. The second loop must testx % 2 != 0. - Sorting with the value as the key, for example
A.sort(). That orders the numbers themselves, so 4 can land before 3 and the groups mix. Usex % 2as the key. - Comparing the result to the Output line with an exact equality check. Other valid orders fail that check. Test the property instead: every even value appears before every odd value.
- Advancing
leftandrightpast a pair that was never checked, such as incrementingleftafter a swap but not decrementingright. The gap then shrinks by one instead of two, which breaks the loop reasoning and can leave a misplaced value unseen.
Edge cases
[0](one element): the loop never runs and[0]is returned, which is correct.[1, 3, 5](all odd):rightwalks to the front,leftstays at 0, and the array is unchanged. That is valid because no even value exists.[2, 4, 6](all even):leftwalks to the end and the array is unchanged, which is valid.[1, 2]:leftstops on 1 andrightstops on 2, so the swap gives[2, 1].[1, 0]and[0, 1]: zero is even, so both inputs must become[0, 1]. The first input swaps once and the second needs no change.[3, 3, 2, 2](duplicates): the two-pointer code returns[2, 2, 3, 3]. Each copy is a separate value, so duplicates need no special handling.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Sort Array By Parity, with how to answer them.
Unlock the follow-upsSort Array By Parity FAQ
What is the time complexity of Sort Array By Parity?
The two-pointer solution runs in O(n) time, because each loop step moves one pointer or swaps a pair, and the gap between the pointers shrinks every step. The sort-based solution runs in O(n log n) time. The two-pass solution also runs in O(n) time but uses O(n) extra space.
Why use two pointers for Sort Array By Parity?
The task is to split one array into two groups in place. Two pointers from opposite ends find the misplaced values on each side, and one swap fixes a pair. The pointers meet after at most n - 1 steps, so the whole array is covered once.
Can Sort Array By Parity be solved in O(1) extra space?
Yes. The two-pointer solution swaps values inside the input and stores only two indices and one temporary value. An in-place sort also avoids a second array, but its library implementation can still use O(log n) or O(n) temporary memory.
Does the answer have to match the example output exactly?
No. The problem accepts any array in which every even value comes before every odd value. The brute force returns the stable order shown in the example, and the two-pointer solution returns a different valid order.
Asked at
See which companies ask this — Pro
Related problems
- Remove Duplicates from Sorted Array · same technique: In-place Array Modification
- Remove Element · same technique: In-place Array Modification
- Merge Strings Alternately · same technique: In-place Array Modification
- Move Zeroes · same technique: In-place Array Modification
- Intersection of Two Arrays · same technique: In-place Array Modification
- Sort Colors · next harder, same pattern
- Happy Number · same pattern: Two Pointers
- Linked List Cycle · same pattern: Two Pointers
- Reverse String · same pattern: Two Pointers
- Squares of a Sorted Array · same pattern: Two Pointers