Sort Array By Parity - Problem

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

Note: The relative order of even and odd numbers doesn't need to be preserved.

Input & Output

Example 1 — Basic Mixed Array
$ Input: nums = [3,1,2,4]
Output: [2,4,3,1]
💡 Note: Even numbers 2 and 4 are moved to the beginning, followed by odd numbers 3 and 1. Note: [4,2,1,3] would also be correct.
Example 2 — Single Element
$ Input: nums = [0]
Output: [0]
💡 Note: Array with single even element remains unchanged.
Example 3 — All Odds Then Evens
$ Input: nums = [1,3,5,2,4,6]
Output: [2,4,6,1,3,5]
💡 Note: All even numbers [2,4,6] are grouped at the beginning, followed by all odd numbers [1,3,5].

Constraints

  • 1 ≤ nums.length ≤ 5000
  • 0 ≤ nums[i] ≤ 5000

Visualization

Tap to expand
Sort Array By Parity ProblemTransform: Mixed → Evens First, Odds Second3124INPUT: [3,1,2,4]oddoddevenevenPARTITION BY PARITY2431OUTPUT: [2,4,3,1]evens firstodds second
Understanding the Visualization
1
Input
Mixed array of even and odd integers
2
Process
Separate evens and odds (various methods)
3
Output
Array with all evens first, then all odds
Key Takeaway
🎯 Key Insight: This is a partitioning problem, not a full sorting problem - we only need to separate by parity
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 5
180.0K Views
Medium Frequency
~8 min Avg. Time
3.2K 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