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 INPUT nums = [4, 2, 5, 7] i=0 i=1 i=2 i=3 4 2 5 7 Even number Odd number Index Parity Rule: Even index (0,2) --> Even value Odd index (1,3) --> Odd value Current Issues: i=1: 2 is even (wrong!) i=2: 5 is odd (wrong!) ALGORITHM STEPS 1 Initialize Pointers evenPtr = 0, oddPtr = 1 2 Find Misplaced Even Scan even indices for odd 3 Find Misplaced Odd Scan odd indices for even 4 Swap Elements Exchange misplaced pair Swap: nums[1] and nums[2] 2 5 --> 5 2 Time: O(n) | Space: O(1) FINAL RESULT Output: [4, 5, 2, 7] i=0 i=1 i=2 i=3 4 5 2 7 Verification: i=0 (even): 4 is even - OK i=1 (odd): 5 is odd - OK i=2 (even): 2 is even - OK i=3 (odd): 7 is odd - OK ALL VALID! return [4, 5, 2, 7] Key Insight: Use two pointers - one scanning even indices, one scanning odd indices. When we find a misplaced odd number at an even index AND a misplaced even number at an odd index, swap them. This guarantees O(n) time with O(1) space since each element is visited at most once. TutorialsPoint - Sort Array By Parity II | Optimal Two-Pointer Approach
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