Sort Array By Parity

Given an integer array nums, move all the even integers to the front of the array, followed by all the odd integers. Any such arrangement is accepted. This walkthrough builds the stable one (evens in their original order, then odds in their original order). Return the rearranged array.

30:00

Sort Array By Parity
easy
Free written solution
Topics
Companies

Given an integer array nums, move all the even integers to the front of the array, followed by all the odd integers. Any such arrangement is accepted. This walkthrough builds the stable one (evens in their original order, then odds in their original order). Return the rearranged array.

Example 1:
Input: {"nums":[3,1,2,4]}
Output: [2,4,3,1]
Constraints:
  • 1≤nums.length≤50001 \leq \text{nums.length} \leq 5000

  • 0≤nums[i]≤50000 \leq \text{nums}[i] \leq 5000

  • Any arrangement with all evens before all odds is accepted.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,1,2,4]}

First pass: count the even numbers among the 4 values, so we know where the odd block must start.

phase setup

evens ?

even ptr -

odd ptr -

nums (read left to right)

3

0

1

1

2

2

4

3

result (even block | odd block)

The output is allocated after counting: the even count says where the odd block begins.

■ even

■ odd

■ being read / just written

Variables
VariableValue
n4
DepthFunction Call
Stack empty
0/11