Sort Array By Parity II - Problem
Imagine you're organizing a dance where partners need to be arranged in a specific pattern! You have an array of integers nums where exactly half are even and exactly half are odd numbers.
Your goal is to rearrange the array so that:
- Every even number sits at an even index (0, 2, 4, ...)
- Every odd number sits at an odd index (1, 3, 5, ...)
For example: [4,2,5,7] becomes [4,5,2,7] where 4 and 2 (even) are at positions 0 and 2, while 5 and 7 (odd) are at positions 1 and 3.
Note: Any valid arrangement that satisfies the condition is acceptable!
Input & Output
example_1.py โ Python
$
Input:
[4,2,5,7]
โบ
Output:
[4,5,2,7]
๐ก Note:
Even numbers 4,2 go to even indices 0,2. Odd numbers 5,7 go to odd indices 1,3. The result satisfies the parity requirement.
example_2.py โ Python
$
Input:
[2,3]
โบ
Output:
[2,3]
๐ก Note:
Already correctly arranged: 2 (even) at index 0 (even), 3 (odd) at index 1 (odd). No changes needed.
example_3.py โ Python
$
Input:
[1,2,3,4]
โบ
Output:
[2,1,4,3]
๐ก Note:
Original has odd numbers at even positions. After rearranging: evens (2,4) at positions (0,2), odds (1,3) at positions (1,3).
Visualization
Tap to expand
Understanding the Visualization
1
Initial Setup
Partners are randomly mixed. We need even-numbered partners at even positions (0,2,4...) and odd-numbered at odd positions (1,3,5...)
2
Two Organizers
Two organizers work simultaneously - one checks even positions, another checks odd positions for misplaced partners
3
Find Mismatches
When both organizers find misplaced partners, they coordinate a swap to fix both positions at once
4
Perfect Arrangement
Continue until all partners are in their correct positions - dance can begin!
Key Takeaway
๐ฏ Key Insight: The two-pointer technique leverages the constraint that we have equal numbers of even and odd elements, allowing us to fix misplacements in pairs with a single swap operation!
Time & Space Complexity
Time Complexity
O(n)
Each pointer traverses the array at most once, and each element is examined at most twice
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for the two pointer variables
โ Linear Space
Constraints
- 2 โค nums.length โค 2 ร 104
- nums.length is even
- Half of the integers in nums are even, and half are odd
- -1000 โค nums[i] โค 1000
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code