#2149. Rearrange Array Elements by Sign

ยท

1 min read

https://leetcode.com/problems/rearrange-array-elements-by-sign/description/?envType=daily-question&envId=2024-02-14

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var rearrangeArray = function (nums) {

    const positive = [], negative = []
    let res = []

    for (const num of nums) {
        if (num > 0) positive.push(num)
        else negative.push(num)
    }

    for (const i in positive) {
        res.push(positive[i])
        res.push(negative[i])
    }

    return res
};

Put al positive and negative in a separate array.

Put the positive and negative into the result array one after the other starting with the positive.

ย