⬅ Previous Topic
Stock Buy and SellNext Topic ⮕
Next Permutation of Array⬅ Previous Topic
Stock Buy and SellNext Topic ⮕
Next Permutation of ArrayTopic Contents
Given an array of integers that contains both positive and negative numbers, your task is to rearrange the elements so that they appear in an alternating order of positive and negative values, starting with a positive number.
If the array is empty or has only one type of number (only positive or only negative), it should be returned as-is.
arr
of integers containing both positive and negative numbers.posIndex = 0
and negIndex = 1
.posIndex
and increment posIndex
by 2.negIndex
and increment negIndex
by 2.def rearrange_alternating_optimal(arr):
n = len(arr)
result = [0] * n
pos_index, neg_index = 0, 1
for num in arr:
if num >= 0 and pos_index < n:
result[pos_index] = num
pos_index += 2
elif num < 0 and neg_index < n:
result[neg_index] = num
neg_index += 2
return result
# Sample Input
arr = [1, 2, 3, -4, -1, 4]
print("Rearranged Array:", rearrange_alternating_optimal(arr))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n) | In the best case, where the array is already alternating with correct signs at correct indices, we still traverse the array once to validate, resulting in linear time. |
Average Case | O(n) | Each element in the array is visited once during the traversal to place it in the correct position, ensuring a single-pass solution. |
Average Case | O(n) | Regardless of the initial arrangement of positive and negative numbers, the array is traversed once and elements are moved in constant time per element. |
O(n)
Explanation: Although the algorithm is optimal in time, it creates a new array to store elements in the correct alternating order, requiring space proportional to the input size.
⬅ Previous Topic
Stock Buy and SellNext Topic ⮕
Next Permutation of ArrayYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.