KatInterview

Interleave Signs With Stable Order and Trailing Zeros

Arrays & HashingAuto-graded · 19 test cases
MediumAuto-gradedArrays & Hashingarraystwo-pointersstable-partition

Last updated

Build a new list that alternates positives and negatives (starting positive), keeps same-sign order, appends leftover elements, and places zeros last.

Interleave Signs With Stable Order and Trailing Zeros

You are given a list of integers values. Return a new list that contains the same elements, arranged by the following rules.

Rules

  1. Alternation. The result begins with a positive number (if any positive exists) and then alternates: positive, negative, positive, negative, and so on. This continues for as long as both a positive and a negative number are still available.
  2. Leftovers. Once one sign runs out, the remaining numbers of the other sign follow immediately, in their original order. At most one sign has leftovers.
  3. Zeros last. Every zero goes at the very end of the result, after everything else. Zeros are neither positive nor negative and do not take part in the alternation.
  4. Stability. Among positives, the relative order from the input is preserved. The same holds for negatives and for zeros.

The starting sign is always positive when at least one positive exists, even if negatives are more numerous.

The output must match exactly, so follow these rules precisely. The result must be a permutation of the input.

Function

Implement interleave_signs(values) that returns the rearranged list.

Constraints

  • 1 <= len(values) <= 10^5
  • -10^9 <= values[i] <= 10^9
  • Aim for O(n) time.

Examples

Example 1

Input: interleave_signs([1, -2, 3, -4, 0, 5])

Output: [1, -2, 3, -4, 5, 0]

Example 2

Input: interleave_signs([-1, -2, 3, 0])

Output: [3, -1, -2, 0]

Example 3

Input: interleave_signs([0, 0, -3, 2, 4, -1, 5])

Output: [2, -3, 4, -1, 5, 0, 0]

Hints

Hint 1

Split the input into three lists by sign (positive, negative, zero), each keeping the input order.

Hint 2

Walk two pointers over the positive and negative lists, emitting one from each per step while both still have elements.

Hint 3

After the paired phase, append whatever remains of either sign list, and only then append all the zeros.