Rearrange Array in Alternating Positive and Negative Items - Optimal Approach

Rearrange Array in Alternating Positive and Negative Items - Optimal Approach

Algorithm Steps

  1. Given an array arr containing both positive and negative integers.
  2. Create two separate lists: one for positive numbers and another for negative numbers while maintaining their order.
  3. Initialize a result array and use two pointers: posIndex = 0 and negIndex = 0.
  4. Start placing elements alternately: first positive, then negative (or vice versa depending on problem constraints).
  5. If one list is exhausted, append the remaining elements of the other list.
  6. Return the rearranged array.

Rearrange Array Alternating Positive and Negative Numbers Code

Python
JavaScript
Java
C++
C
def rearrange_alternating(arr):
    pos = [x for x in arr if x >= 0]
    neg = [x for x in arr if x < 0]
    result = []
    i = j = 0
    while i < len(pos) and j < len(neg):
        result.append(pos[i])
        result.append(neg[j])
        i += 1
        j += 1
    result.extend(pos[i:])
    result.extend(neg[j:])
    return result

# Sample Input
arr = [1, 2, 3, -4, -1, 4]
print("Rearranged Array:", rearrange_alternating(arr))