Problem 223662 · easy · Phase 02 Linear Data Structures

Evens First, Order Kept

arrays · stable partition · predicates

Given a list of integers nums, return a new list containing all the even numbers first, followed by all the odd numbers. Within each group the numbers must keep the order they had in nums.

Examples

Input:  nums = [3, 8, 5, 6, 1, 2]
Output: [8, 6, 2, 3, 5, 1]
Explanation: evens 8, 6, 2 keep their order; odds 3, 5, 1 keep theirs.

Input:  nums = [0, -1, -2, -3]
Output: [0, -2, -1, -3]

Constraints

  • 0 <= len(nums) <= 10**5
  • Return a new list; do not sort.
  • Target: O(n) time.

Goals

  • Partition a list by a predicate without sorting
  • Preserve the relative order inside each group
  • Treat zero and negative numbers correctly with the modulo operator
Starting Python…