Problem 333096 · easy · Phase 03 Linear Management & Searching

Evens Before Odds In Place

two pointers · in-place · partition

Given a list of integers nums, rearrange it in place so that every even number comes before every odd number (order inside each group does not matter). Return the number of even values, i.e. the index where the odd values begin.

Tests call (k := evens_first(a := [...]), k, sorted(a[:k]), sorted(a[k:]))[1:].

Examples

Input:  nums = [3, 1, 2, 4]
Output: 2; nums becomes e.g. [4, 2, 1, 3]

Input:  nums = [1, 3, 5]
Output: 0

Constraints

  • 0 <= len(nums) <= 10**5
  • Target: O(n) time, O(1) extra space.

Goals

  • Partition by a boolean predicate with pointers from both ends
  • Return the boundary between the two regions
Starting Python…