Problem 322635 · medium · Level 03 Linear Management & Searching

Interleave the Credits and Debits

two pointers · arrays · partition

A bank statement nums lists credits (zero or positive amounts) and debits (negative amounts). For a summary view, build a new list that goes credit, debit, credit, debit, and so on, starting with a credit whenever there is one. Credits keep their original order among themselves, and so do debits. Once one kind runs out, add all remaining entries of the other kind in their original order. An amount of zero counts as a credit.

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…