Skip to main content

Rearrange Array Elements by Sign - Solution & Explanation

MediumArrayTwo PointersSimulation15 min readAsked at: Amazon, Microsoft, Meta +3
Practice this problem

Problem Statement

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 the array follows the given conditions:

  1. Every consecutive pair of integers have opposite signs.
  2. For all integers with the same sign, the order in which they were present in nums is preserved.
  3. The rearranged array begins with a positive integer.

Return the modified array after rearranging the elements to satisfy the aforementioned conditions.

 

Example 1:

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].
The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4].
Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions.  

Example 2:

Input: nums = [-1,1]
Output: [1,-1]
Explanation:
1 is the only positive integer and -1 the only negative integer in nums.
So nums is rearranged to [1,-1].

 

Constraints:

  • 2 <= nums.length <= 2 * 105
  • nums.length is even
  • 1 <= |nums[i]| <= 105
  • nums consists of equal number of positive and negative integers.

 

It is not required to do the modifications in-place.

Approach Overview

Problem Overview: You are given an array with equal numbers of positive and negative integers. Rearrange the elements so positives and negatives appear alternately, starting with a positive number, while preserving the relative order of elements.

Approach 1: Two Lists Approach (O(n) time, O(n) space)

Split the array into two separate lists: one for positive numbers and one for negative numbers. Iterate through the original array once and push values into the corresponding list. Then construct the result by alternating elements from both lists: positive at even indices and negative at odd indices. Since the problem guarantees equal counts of positives and negatives, both lists will be exhausted at the same time. This approach is straightforward and preserves relative order naturally because elements are appended in the order they appear. It’s commonly used when solving array rearrangement problems where stability matters.

Approach 2: In-place Rearrangement (O(n) time, O(1) extra space)

Instead of maintaining two auxiliary lists, place elements directly into their correct positions using index pointers. Maintain two indices: one pointing to the next even index (for positives) and another pointing to the next odd index (for negatives). Iterate through the array and place each value in the correct index based on its sign. After placing a number, move the corresponding pointer by two positions. The key insight is that positives must occupy even indices (0,2,4...) while negatives occupy odd indices (1,3,5...). This keeps the alternating pattern intact without storing intermediate lists. The technique resembles a controlled placement strategy often used with two pointers and simple simulation logic.

Both strategies run in linear time because each element is processed once. The difference is memory usage: the two-list solution trades space for clarity, while the in-place strategy minimizes auxiliary storage.

Recommended for interviews: The two lists approach is usually the first solution candidates implement because it clearly demonstrates understanding of the alternating constraint and order preservation. Interviewers often expect the O(n) time complexity solution quickly. After that, discussing the in-place rearrangement shows deeper optimization skills and awareness of space complexity tradeoffs.

Approach 1: Two Lists Approach

This approach involves creating two separate lists to store positive and negative numbers. After separating, we iterate through both lists simultaneously, placing elements alternatively from each into a new result list. This ensures that conditions for alternating signs and preserving order are met.

This C program separates the positive and negative numbers into two arrays, then fills the result array in alternating order.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n); Space Complexity: O(n).

Try this approach in the editor β†’

Approach 2: In-place Rearrangement

This approach attempts to rearrange the array in-place with the help of two pointers: one for the next positive element and one for the next negative. Starting with the assumption that the first element should be positive, iterate over the array and swap elements to their correct positions as needed.

In this in-place C solution, pointers keep track of the correct next position for positive and negative elements, swapping where necessary.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n); Space Complexity: O(1).

Try this approach in the editor β†’

Approach 3: Two Pointers

First, we create an array ans of length n. Then, we use two pointers i and j to point to the even and odd indices of ans, respectively, with initial values i = 0, j = 1.

We iterate through the array nums. If the current element x is a positive integer, then we place x into ans[i] and increase i by 2; otherwise, we place x into ans[j] and increase j by 2.

Finally, we return ans.

The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor β†’

Complexity Comparison

ApproachComplexity
Two Lists Approach

Time Complexity: O(n); Space Complexity: O(n).

In-place Rearrangement

Time Complexity: O(n); Space Complexity: O(1).

Two Pointersβ€”

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Two Lists ApproachO(n)O(n)Best for clarity and quick implementation when extra memory is acceptable.
In-place RearrangementO(n)O(1)Useful when memory is constrained or when interviewers ask for optimized space usage.
Two-Pointer Placement with Result ArrayO(n)O(n)Good balance of simplicity and speed when directly filling even and odd indices.

Video Solution

Rearrange Array Elements by Sign | 2 Varieties of same Problem β€’ take U forward β€’ 526,209 views views

Watch 9 more video solutions β†’

Frequently Asked Questions

Is Rearrange Array Elements by Sign easy or hard?
The problem is rated Medium but behaves closer to an easy-medium array manipulation task. The logic is straightforward once you recognize the alternating index pattern, but the requirement to preserve relative order makes it slightly more involved than a simple partition problem.
Rearrange Array Elements by Sign Python/Java solution
In Python or Java, iterate through the array and push positive values into one list and negative values into another. Then build the result by alternating elements from both lists. This produces an O(n) solution that preserves the original ordering of numbers.
How to solve Rearrange Array Elements by Sign in O(n)?
Traverse the array once and place each positive number at the next available even index and each negative number at the next odd index. Maintain two pointers that move by two positions after each placement. Every element is processed exactly once, giving O(n) time complexity.
What is the best approach for Rearrange Array Elements by Sign?
The most practical approach uses two lists to collect positive and negative numbers separately, then alternates them in the result array. This method runs in O(n) time and preserves the relative order of elements. It is simple to implement and is the approach most candidates write first during interviews.
Is Rearrange Array Elements by Sign asked at Google/Amazon/Meta?
Array rearrangement and alternating placement patterns appear frequently in interviews at companies like Amazon, Google, and Meta. While the exact problem may vary, the underlying techniques such as two pointers, index placement, and stable ordering are common interview topics.
What data structure is used in Rearrange Array Elements by Sign?
The problem primarily uses arrays and sometimes auxiliary lists (dynamic arrays) to store positive and negative values. The optimized solution relies on pointer indices within the array rather than additional data structures.
What is the time complexity of Rearrange Array Elements by Sign?
The optimal solutions run in O(n) time because the array is traversed once to separate or place elements and once to construct the final arrangement. Space complexity is either O(n) when using auxiliary lists or O(1) when using an in-place placement strategy.

Ready to solve this problem?

Practice Rearrange Array Elements by Sign with our built-in code editor and test cases.

Practice on FleetCode