DevPath

← All problems

Sort Array By Parity

Easy arrays · two-pointers

Description

Return the array with all even numbers first, followed by all odd numbers, preserving the relative order within each group.

Constraints

1 <= n <= 100000

Examples

Input: nums = [3,1,2,4]

Output: [2,4,3,1]

Hints (1)
  • Collect evens and odds separately, then concatenate.

Solutions

Partition into evens and odds, then merge. · Time O(n) · Space O(n)

func sortByParity(nums []int) []int {
    evens := []int{}
    odds := []int{}
    for _, n := range nums {
        if n%2 == 0 {
            evens = append(evens, n)
        } else {
            odds = append(odds, n)
        }
    }
    return append(evens, odds...)
}

Create a free account to submit solutions, track progress and save problems.

Create account