Python Program to Rearrange the array in alternating positive and negative items with O(1) extra space
Login/Signup to comment
Login/Signup to comment
Get Hiring Updates right in your inbox from PrepInsta
def rearrange_array_in_alternating_positive_and_negative_items(arr):
n = len(arr)
i, j = 0, n-1
while (i<j):
while (i 0):
i += 1
while (j >= 0 and arr[j] < 0):
j -= 1
if (i < j):
arr[i], arr[j] = arr[j], arr[i]
if i ==0 and i == n:
return
k = 0
while i < n and k < n:
arr[i], arr[k] = arr[k], arr[i]
i += 1
k += 2
return arr
arr = [2, 7, 8, -3, -17, -4, -6, -5]
print(rearrange_array_in_alternating_positive_and_negative_items(arr))
a=[2, 3, -4, -1, 6, -9]
p=0
for i in range(0,len(a)):
if a[i]<0:
a[p],a[i]=a[i],a[p]
p+=2
print(a)
Kindly refer to our discord community for all your technical doubts.