Unicorns VO Coding Interview Question: Rearrange Array to Alternate Positive and Negative Numbers

13 Views
No Comments

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 these conditions:

  • Every consecutive pair of integers have opposite signs.
  • For all integers with the same sign, the order in which they were present in nums is preserved.
  • 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].

This problem asks you to rearrange an even-length array so that positive and negative numbers alternate, starting with a positive number, while preserving the original relative order among numbers with the same sign. The standard approach is to collect positives and negatives in order, then rebuild the result by placing positives at even indices and negatives at odd indices.

END
 0