Sort Array By Parity II

Even-valued at even indices, odd-valued at odd indices — two interleaved pointers.

Easy
Time O(n) Space O(1)
LeetCode
3 min read
cyclic-sort two-pointers

Problem#

Rearrange nums so that even values sit at even indices and odd values at odd indices.

Examples#

  • [4,2,5,7][4,5,2,7]

Constraints#

  • 2 <= n <= 2 * 10^4, half even half odd.

Approach#

Two pointers e = 0 (even index), o = 1 (odd index). Advance e while nums[e] is even; advance o while nums[o] is odd. Swap when both are misplaced.

Solution#

Sort Array By Parity II
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
int e = 0, o = 1, n = nums.size();
while (e < n && o < n) {
if (nums[e] % 2 == 0) e += 2;
else if (nums[o] % 2 == 1) o += 2;
else { swap(nums[e], nums[o]); e += 2; o += 2; }
}
return nums;
}
};

Editorial#

Each swap fixes two cells simultaneously. The two-pointer walk costs O(n).

Complexity#

  • Time: O(n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.