Rearrange Array Elements by Sign

You are given an even-length integer array nums with as many positive as negative integers. Rearrange it so that signs alternate starting with a positive number, while the positives keep their original relative order and the negatives keep theirs. Return the rearranged array.

30:00

Rearrange Array Elements by Sign
medium
Free written solution
Topics
Companies

You are given an even-length integer array nums with as many positive as negative integers. Rearrange it so that signs alternate starting with a positive number, while the positives keep their original relative order and the negatives keep theirs. Return the rearranged array.

Example 1:
Input: {"nums":[3,1,-2,-5,2,-4]}
Output: [3,-2,1,-5,2,-4]
Constraints:
  • 2≤nums.length≤2⋅1052 \leq \text{nums.length} \leq 2 \cdot 10^5

  • nums.length is even

  • 1≤∣nums[i]∣≤1051 \leq |\text{nums}[i]| \leq 10^5

  • nums has equally many positive and negative integers.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,1,-2,-5,2,-4]}

Make an output of 6 slots. Even slots (0, 2, 4, ...) will hold positives and odd slots (1, 3, 5, ...) negatives.

pos -

neg -

positives seated 0/3

negatives seated 0/3

nums (arrival order)

3

0

1

1

-2

2

-5

3

2

4

-4

5

result seats (+ at even index, − at odd index)

+

0

−

1

+

2

−

3

+

4

−

5

■ positive / even seat

■ negative / odd seat

■ being read / just seated

Variables
VariableValue
n6
DepthFunction Call
Stack empty
0/8