Problem 322635 · medium · Phase 03 Linear Management & Searching

Alternate Positive and Negative

two pointers · arrays · partition

Given a list of integers nums, return a new list that alternates non-negative and negative values, starting with a non-negative value if there is one. Values of each sign must keep their original relative order. When one sign runs out, append the remaining values of the other sign in order. Zero counts as non-negative.

Examples

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

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

Input:  nums = [-4, -5]
Output: [-4, -5]

Constraints

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

Goals

  • Split by sign while keeping each group's original order
  • Interleave two sequences with independent read pointers and append the leftovers
Starting Python…