Problem 205081 · medium · Phase 02 Linear Data Structures

Alternate Positives and Negatives

arrays · stable partition · interleaving

Given a list of non-zero integers nums containing exactly as many positive numbers as negative numbers, return a new list in which positive and negative numbers alternate, starting with a positive number. The positives must keep their original relative order, and so must the negatives.

Examples

Input:  nums = [3, 1, -2, -5, 2, -4]
Output: [3, -2, 1, -5, 2, -4]
Explanation: positives 3, 1, 2 and negatives -2, -5, -4 are interleaved.

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

Constraints

  • 0 <= len(nums) <= 10**5, length is even, no zeros
  • Return a new list.
  • Target: O(n) time.

Goals

  • Separate a list by sign while keeping order
  • Interleave two equally long groups
  • Guarantee the result starts with a positive
Starting Python…