Sort Array By Parity
Easy · Arrays & Hashing · Array · Two Pointers · Sorting
Problem
You are given an integer array nums.
Rearrange it so that every even value comes before every odd value, and return the result. The order inside the evens, and inside the odds, does not matter: any evens-first arrangement is accepted.
Try to do it in place, in one pass.
Examples
Input: nums = [7,2,5,8] Output: [8,2,5,7]
The evens 8 and 2 come first. [2,8,7,5], or any other evens-first order, is accepted too.
Input: nums = [5,4,5,4] Output: [4,4,5,5]
Both 4s first, then both 5s.
Input: nums = [1] Output: [1]
A single value is already arranged.
Constraints
- 1 <= len(nums) <= 5000
- 0 <= nums[i] <= 5000
Approaches
- Baseline: sort by parity — time O(n log n), space O(n)
Follow-up
If the evens and the odds must keep their input order, the swaps no longer work; collect each group in one pass and join them (see the use case "Evens first, keeping the order"). Doing that stable split in place with O(1) extra space is much harder.
Related problems
Start free on Cariara · Coding problems · System design studio