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 INPUT nums = [3, 1, 2, 4] 3 odd 1 odd 2 even 4 even i=0 i=1 i=2 i=3 Even numbers Odd numbers Goal: Move all evens to front Move all odds to back ALGORITHM STEPS 1 Two Pointers left=0, right=n-1 2 Scan from left Find odd number 3 Scan from right Find even number 4 Swap elements Repeat until done Swap Process: Before: 3 4 After: 4 3 FINAL RESULT Output: [2, 4, 3, 1] 2 even 4 even 3 odd 1 odd partition OK - Sorted! Evens first, odds last Complexity: Time: O(n) Space: O(1) Key Insight: Two-pointer technique partitions the array in-place. Left pointer finds odds, right pointer finds evens. Swap them until pointers meet. No extra space needed, single pass through array achieves O(n) time. TutorialsPoint - Sort Array By Parity | Two-Pointer Optimal Approach
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