Problem 205081 · easy · Level 02 Linear Data Structures

Gains and Losses Taking Turns

arrays · stable partition · interleaving

A trader's ledger nums holds non-zero amounts: gains are positive, losses are negative, and there are exactly as many gains as losses. For a chart she wants them interleaved as gain, loss, gain, loss, and so on, always starting with a gain. The gains must stay in the order they were recorded, and so must the losses. Return the interleaved ledger as a new list.

Examples

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

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

Constraints

  • No value is zero and the length is even.
  • 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…