Sort Array By Parity II (LeetCode 922): Solution and Explanation

Easy
Array
Two Pointers
Sorting

Rearrange an array that is half even and half odd so even indices hold even values and odd indices hold odd values. Any valid arrangement is accepted.

Intuition

Because exactly half the values are even, every odd value sitting at an even index is matched by an even value sitting at an odd index. Misplaced values always come in pairs.

Swapping one member of each pair fixes two slots at once, so we only need to find the pairs.

One pointer walks the even indices looking for odd values; another walks the odd indices looking for even values. The second pointer never has to go back, because every odd slot it passed already holds an odd value.

Approach: Two pointers on even and odd slots

  1. Set j = 1, the first odd index.
  2. Step i through the even indices 0, 2, 4, and so on.
  3. If nums[i] is odd, advance j by 2 while nums[j] is odd.
  4. Swap nums[i] and nums[j]. Both slots now hold the right parity.
  5. Return nums.

Step-by-step example

nums = [4,2,5,7]
  1. i = 0: 4 is even in an even slot, nothing to do.
  2. i = 2: 5 is odd in an even slot. Check j = 1: nums[1] = 2 is even, so it is the partner.
  3. Swap nums[2] and nums[1]: [4,5,2,7].
  4. The even-index loop ends. Return [4,5,2,7].

Code: Python, Java, C++

1class Solution:
2    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
3        j = 1
4        for i in range(0, len(nums), 2):
5            if nums[i] % 2 == 1:
6                while nums[j] % 2 == 1:
7                    j += 2
8                nums[i], nums[j] = nums[j], nums[i]
9        return nums
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

i visits each even index once and j moves forward over each odd index at most once.

Space

O(1)

The swaps happen in place, using only the two pointers.

Other approaches

Two output buckets (time O(n), space O(n))

Write even values to indices 0, 2, 4, ... and odd values to 1, 3, 5, ... of a new array in one scan. Very simple, but uses an extra array.

Separate then interleave (time O(n), space O(n))

Collect the evens and the odds into two lists, then interleave them. Same cost as the bucket approach with an extra pass.

Common mistakes

  • Resetting j to 1 for every misplaced value, which makes the scan quadratic.
  • Moving j by 1 instead of 2, which lets it land on even slots.
  • Expecting a single exact output. Many arrangements are correct, and any of them is accepted.

Frequently asked questions

Why can j never run past the end of the array?

When nums[i] is odd at an even slot, there must still be an even value at some odd slot ahead of j, because the counts of evens and odds are equal.

Is the output unique?

No. Any array with even values at even indices and odd values at odd indices is accepted, so a checker verifies the rule instead of comparing to one answer.

How is this different from Sort Array By Parity I?

Part I only asks for all evens before all odds. Part II interleaves them by index, so the pointers step by 2 over fixed slot types.