Sort Array By Parity II - Problem

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,5,7]
Output: [4,5,2,7]
💡 Note: Index 0 (even) has 4 (even) ✓, index 1 (odd) needs odd number, so we place 5. Index 2 (even) gets remaining even 2, index 3 (odd) gets remaining odd 7.
Example 2 — Already Correct
$ Input: nums = [2,3]
Output: [2,3]
💡 Note: Index 0 (even) has 2 (even) ✓, index 1 (odd) has 3 (odd) ✓. Array is already correctly arranged.
Example 3 — Larger Array
$ Input: nums = [4,2,5,7,8,9]
Output: [4,5,2,7,8,9]
💡 Note: Even indices (0,2,4) should have even numbers (4,2,8) and odd indices (1,3,5) should have odd numbers (5,7,9). One valid arrangement is [4,5,2,7,8,9].

Constraints

  • 2 ≤ nums.length ≤ 2 × 104
  • nums.length is even
  • Half of integers in nums are even
  • 0 ≤ nums[i] ≤ 1000

Visualization

Tap to expand
Sort Array By Parity II: Arrange by Index-Value Parity MatchInput: [4,2,5,7]42570123Rule: Even indices (0,2,4...) must have even numbersOdd indices (1,3,5...) must have odd numbersOutput: [4,5,2,7]4527evenoddevenodd✓ Every even index has even number, every odd index has odd number
Understanding the Visualization
1
Input
Array with mixed even/odd numbers at any position
2
Constraint
Even numbers must go to even indices, odds to odd indices
3
Output
Rearranged array satisfying the parity constraint
Key Takeaway
🎯 Key Insight: Match the parity (even/odd) of array indices with the parity of their values
Asked in
Facebook 15 Apple 12 Google 8 Amazon 6
125.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen