Rearrange Array Elements by Sign — LeetCode 2149 Python Solution

MediumArrayTwo PointersSimulation
Problem
#2149
Reading time
2 min

The problem

You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should return the array of nums such that the array follows the given conditions: Every consecutive pair of integers have opposite signs.

Example

Input
nums = [3,1,-2,-5,2,-4]
Output
[3,-2,1,-5,2,-4]
Explanation
The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4].

Python solution

Python
class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        ans = [0] * len(nums)
        i, j = 0, 1
        for x in nums:
            if x > 0:
                ans[i] = x
                i += 2
            else:
                ans[j] = x
                j += 2
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 2149. Rearrange Array Elements by Sign is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2149. Rearrange Array Elements by Sign?
LeetCode 2149. Rearrange Array Elements by Sign is rated Medium on LeetCode.
What is the time complexity of LeetCode 2149. Rearrange Array Elements by Sign?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2149. Rearrange Array Elements by Sign?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2149. Rearrange Array Elements by Sign cover?
LeetCode 2149. Rearrange Array Elements by Sign is tagged Array, Two Pointers and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview