Skip to main content
Back to problems
Leetcode
Medium
Arrays
Amazon
Rearrange Array Elements By Sign

Reorder an array so positive and negative values appear in alternating order while preserving their original relative order within each sign group.

Acceptance 100%
Problem Statement

Given an integer array nums containing the same number of positive and negative integers, rearrange the elements so that:

  • positive and negative numbers appear in alternating order, and
  • the first element is positive.

Keep the relative order of the positive numbers the same as in the original array, and do the same for the negative numbers.

Return the rearranged array.

Input Format

  • An integer array nums.
  • nums contains an equal number of positive and negative integers.
  • Every element is non-zero.

Output Format

  • Return an array of the same length as nums.
  • The returned array must alternate positive and negative values, starting with a positive value.

Constraints

  • 2nums.length1052 \le nums.length \le 10^5
  • nums.length is even
  • nums[i] != 0
  • The number of positive integers equals the number of negative integers
  • Preserve relative order among positive numbers and among negative numbers
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [3,1,-2,-5,2,-4]

Output

[3,-2,1,-5,2,-4]

Explanation

Positive numbers keep their order: [3,1,2]. Negative numbers keep their order: [-2,-5,-4]. Placing them alternately starting with a positive number gives [3,-2,1,-5,2,-4].

Example 2

Input

nums = [-1,1]

Output

[1,-1]

Explanation

The array must start with a positive number, so the only valid rearrangement is [1,-1].

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.