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
Party Line Organization AnalogyCouples (Even) must come before Singles (Odd)Before: Mixed Queue3Single1Single2Couple4CoupleProcess: Two Organizers WorkingLEFTFront OrganizerRIGHTScannerMove CoupleAfter: Organized Queue2431COUPLES FIRSTSINGLES AFTER๐Ÿ’ก Key InsightInstead of moving everyone aroundmultiple times, we strategicallyplace each person directly intheir correct zone with justONE PASS!
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.
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
85.2K 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