Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Sort Array By Parity II

Rearrange an array so that even values appear at even indices and odd values appear at odd indices.

Acceptance 0%
Problem Statement

Given an integer array nums with an equal number of even and odd values, rearrange the array so that:

  • nums[i] is even when i is even
  • nums[i] is odd when i is odd

Return any valid rearrangement. You may modify the array in place or return a new array, depending on your implementation choice.

The input is guaranteed to contain the same number of even and odd elements, so a valid arrangement always exists.

Input Format

  • An integer array nums
  • nums contains an equal count of even and odd integers

Output Format

  • Return an array rearranged so parity matches index parity at every position

Constraints

  • 2 <= nums.length <= 2 * $10^{4}$
  • nums.length is even
  • nums contains an equal number of even and odd integers
  • All values fit in standard 32-bit signed integers
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [4,2,5,7]

Output

[4,5,2,7]

Explanation

Index 0 and 2 contain even numbers, while index 1 and 3 contain odd numbers.

Example 2

Input

nums = [2,3]

Output

[2,3]

Explanation

The array already satisfies the required parity arrangement.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.