Skip to content

Rearrange the array in alternating positive and negative items ​

Rearrange the array in alternating positive and negative items — LeetCode

Given an array with an equal number of positive and negative integers, rearrange it so the signs alternate starting with a positive, preserving the relative order within each sign.

Approach ​

Set p = 0, n = 1 Go from 0 - N, if num[i] is positive, place it in res[p], increment p += 2; Else place it in res[n] and move n += 2.

Remarks ​

I thought of the other way around. I placed the p and n on the actual input array, and tried to find the next positive and negative on each iteration.