Sort Array By Parity II

Given an array of integers `nums`, half of the integers in `nums` are **odd**, and the other half are **even**. Sort the array so that whenever `nums[i]` is odd, `i` is **odd**, and whenever `nums[i]` is even, `i` is **even**. Return *any answer array that satisfies this condition*.

30:00

Sort Array By Parity II
easy
Free written solution
Topics
Companies

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.

Example 1:
Input: {"nums":[4,2,5,7]}
Output: [4,5,2,7]
Constraints:
  • 2≤nums.length≤2×1042 \leq \text{nums.length} \leq 2 \times 10^4

  • nums.length is even.

  • Half of the integers in nums are even.

  • 0≤nums[i]≤10000 \leq \text{nums}[i] \leq 1000

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

Run code to see results.

Input
arr ={"nums":[4,2,5,7]}

Even slots (0, 2, 4, ...) must hold even values and odd slots must hold odd values. 1 even slot holds an odd value, so the same number of odd slots hold an even value.

even slots
i
4
0
5
✕
2
odd slots
2
✕
1
j
7
3

i (even slot)

0

j (odd slot)

1

swaps

0

misplaced

2

even value
odd value
wrong slot (✕)
swapped now
i walks even slots
j walks odd slots
Variables
VariableValue
i0
j1
nums[i]4
nums[j]2
swaps0
DepthFunction Call
Stack empty
0/5