15% off all plans & roadmaps Use code

See plans

Sort Array By Parity

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 <= 5000
  • 0 <= 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 % 2 returns 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.

View on LeetCode

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.

Watch the pattern animation

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

  1. Create an empty result list with room for n values.
  2. Scan nums from left to right and append each even value to the result.
  3. Scan nums again from left to right and append each odd value to the result.
  4. 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

TimeO(n)
SpaceO(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 + odds

Approach 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

  1. Define the key of each value as x % 2, which is 0 for even and 1 for odd.
  2. Sort the array by that key, using the language's sort with a key or comparator.
  3. 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

TimeO(n log n)
SpaceO(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 A

The 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 infographic

Solution 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

  1. Set left to 0 and right to n - 1.
  2. While left < right, check A[left]. If it is even, add 1 to left and go back to the loop test.
  3. Otherwise check A[right]. If it is odd, subtract 1 from right and go back to the loop test.
  4. Otherwise A[left] is odd and A[right] is even. Swap them, then add 1 to left and subtract 1 from right.
  5. 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.

StepleftrightA[left]A[right]ActionArray after
107565 is odd and 6 is even, so swap and move both[6, 2, 7, 8, 1, 4, 3, 5]
216232 is even, so move left[6, 2, 7, 8, 1, 4, 3, 5]
326737 is odd and 3 is odd, so move right[6, 2, 7, 8, 1, 4, 3, 5]
425747 is odd and 4 is even, so swap and move both[6, 2, 4, 8, 1, 7, 3, 5]
534818 is even, so move left[6, 2, 4, 8, 1, 7, 3, 5]
64411left 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

TimeO(n)
SpaceO(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 A

Common mistakes

  • elif A[right] % 2 == 0: on the right side. This moves right past the even values, which are the values that must leave the right side. Advance right only when the value is odd, with A[right] % 2 != 0.
  • Swapping whenever A[left] is odd, without checking A[right]. If both values are odd, the swap changes nothing, yet both pointers move and an odd value stays inside the even prefix. Check A[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 test x % 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. Use x % 2 as 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 left and right past a pair that was never checked, such as incrementing left after a swap but not decrementing right. 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): right walks to the front, left stays at 0, and the array is unchanged. That is valid because no even value exists.
  • [2, 4, 6] (all even): left walks to the end and the array is unchanged, which is valid.
  • [1, 2]: left stops on 1 and right stops 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-ups

Sort 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

Practise it