Show problems as
Classic problem #2149MediumArrayTwo PointersSimulation

Rearrange Array Elements by Sign

Real-world version: Interleaving the Statement Lines
Tracked in this browser only
Read Rearrange Array Elements by Sign on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A bookkeeper is re-issuing a statement. The old statement is nums, one signed amount per line: a positive amount is a credit and a negative amount is a debit. No line is ever zero, the statement has an even number of lines, and it holds exactly as many credits as debits.

House style says the re-issued statement must read credit, debit, credit, debit, and so on, beginning with a credit. Within each kind, the bookkeeper must not shuffle anything: if one credit came before another credit on the old statement, it must still come before it on the new one, and the same holds for the debits.

Return the re-issued statement as a list of amounts in order. Exactly one arrangement satisfies house style.

Examples

Example 1

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

The old statement's credits are 3 then 4 and its debits are -1 then -2. The re-issued statement alternates from a credit and each kind is still in its old sequence.

Example 2

Input
nums = [9, -4, -7, 2, 5, -3]
Output
[9, -4, 2, -7, 5, -3]

Credits appear as 9, 2, 5 and debits as -4, -7, -3. Reading the answer, the odd slots hold those debits in that same order and the even slots hold those credits in theirs.

Example 3

Input
nums = [1, -1]
Output
[1, -1]

Two lines only. The credit takes the first slot and the debit the second.

Example 4

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

Both credits are 5 and both debits are -5, so any credit-first alternation matches house style, and the answer alternates from a credit.

Example 5

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

Here the old statement opens with all three debits. The re-issued one still begins with a credit, taking 3, 2, 1 in that order for the even slots and -1, -2, -3 for the odd slots.

Constraints

  • 2 <= nums.length <= 2 * 10^5
  • nums.length is even
  • 1 <= |nums[i]| <= 10^5
  • nums holds an equal number of positive and negative amounts.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def rearrange_array(nums: list[int]) -> list[int]:
Java
public int[] rearrangeArray(int[] nums)