Sort Array By Parity - Problem
You are given an integer array nums and need to rearrange it so that all even integers come before all odd integers.
Your task is to move all even numbers to the beginning of the array followed by all odd numbers. The relative order within even or odd numbers doesn't matter - any valid arrangement is acceptable.
Example: [3,1,2,4] could become [2,4,3,1] or [4,2,1,3]
Return any array that satisfies this condition where evens come first, then odds.
Input & Output
example_1.py โ Basic Case
$
Input:
[3,1,2,4]
โบ
Output:
[2,4,3,1]
๐ก Note:
The even numbers 2 and 4 are moved to the beginning, followed by odd numbers 3 and 1. Note that [4,2,1,3] would also be a correct answer.
example_2.py โ All Odds
$
Input:
[0]
โบ
Output:
[0]
๐ก Note:
Single element array with an even number remains unchanged since 0 is even.
example_3.py โ Mixed Case
$
Input:
[1,3,5,2,4,6]
โบ
Output:
[2,4,6,1,3,5]
๐ก Note:
All even numbers [2,4,6] come first, then all odd numbers [1,3,5]. The relative order within each group can vary.
Constraints
- 1 โค nums.length โค 5000
- 0 โค nums[i] โค 5000
- Any valid arrangement where evens come before odds is acceptable
Visualization
Tap to expand
Understanding the Visualization
1
Setup Two Organizers
One organizer (left pointer) reserves spots at the front for couples, another (right pointer) scans the line
2
Find and Move Couples
When the scanner finds a couple, swap them to the front position and advance the front organizer
3
Continue Process
Keep scanning until the entire line is processed - all couples will be at the front
4
Perfect Organization
The line is now perfectly organized with couples first, singles after
Key Takeaway
๐ฏ Key Insight: Two pointers allow us to rearrange elements in a single pass by maintaining one pointer for placement and another for discovery, eliminating the need for extra space or multiple iterations.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code