easy

Sort Array By Parity

Rearrange an array so every even value comes before every odd value.

1. Define the problem

Sort Array By Parity

Given an integer array nums, move all the even integers to the beginning of the array, followed by all the odd integers . Any order within each group is acceptable, so any valid answer will be accepted. Use two pointers starting at the left and right ends, swapping an odd value found on the left with an even value found on the right as they converge toward the middle.

Constraints

  • 1 ≤ nums.length ≤ 5000
  • 0 ≤ numsi ≤ 5000

Example

Inputnums = [3, 1, 2, 4]
Output[4, 2, 1, 3]

Explanation Any arrangement with the evens before the odds is accepted; this two-pointer trace produces [4, 2, 1, 3].

2. Visualize the solution

Swap an odd from the left with an even from the right

Swap an odd from the left with an even from the right
Statusinit

left=0 (3) is odd, right=3 (4) is even — both are on the wrong side, about to swap.

What happens in this step

left = 0 (value 3, odd), right = 3 (value 4, even)

Neither pointer can advance on its own (left isn't even, right isn't odd), so this is a genuine mismatch pair — about to swap.
Step 1 of 3

Steps to visualize

  1. Place one pointer at the start and one at the end of the array.
  2. Move the left pointer right while it sits on an even value.
  3. Move the right pointer left while it sits on an odd value.
  4. Swap the odd value at the left with the even value at the right.
  5. Repeat until the pointers meet or cross.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Swap an odd from the left with an even from the right
Statusinit

left=0 (3) is odd, right=3 (4) is even — both are on the wrong side, about to swap.

What happens in this step

left = 0 (value 3, odd), right = 3 (value 4, even)

Neither pointer can advance on its own (left isn't even, right isn't odd), so this is a genuine mismatch pair — about to swap.
Step 1 of 3
4. Solution

Solution

solution.tsTypeScript
function sortArrayByParity(nums) {
  let left = 0;
  let right = nums.length - 1;

  while (left < right) {
    if (nums[left] % 2 === 0) {
      left++;
    } else if (nums[right] % 2 !== 0) {
      right--;
    } else {
      const temp = nums[left];
      nums[left] = nums[right];
      nums[right] = temp;
      left++;
      right--;
    }
  }

  return nums;
}
Time
O(n)
Space
O(1)
5. Test cases

Test cases

InputExpectedCovers
nums = [3, 1, 2, 4][4, 2, 1, 3]example from the docstring
nums = [2, 4, 6][2, 4, 6]every value is already even
nums = [1, 3, 5][1, 3, 5]every value is odd
nums = [2, 4, 1, 3][2, 4, 1, 3]already sorted by parity, no swaps needed
nums = [1][1]smallest valid input, a single element
nums = [1, 2][2, 1]boundary case, exactly two elements requiring one swap
nums = [3, 1, 2, 4, 6, 5][6, 4, 2, 1, 3, 5]several swaps required across a longer array